admin管理员组

文章数量:1355123

I try to match/get all repetitions in a string. This is what I've done so far:

var str = 'abcabc123123';
var REPEATED_CHARS_REGEX = /(.).*\1/gi;

console.log( str.match(REPEATED_CHARS_REGEX) ); // => ['abca', '1231']

As you can see the matching result is ['abca', '1231'], but I excpect to get ['abc', '123']. Any ideas to acplish that?

2nd question:

Another thing I excpect, is to make it possible to change the duration how often a char needs to be in the string to get matched...

For example if the string is abcabcabc and the repetation-time is set to 2 it should result in ['abcabc']. If set to 3 it should be ['abc'].

Update

A non-RegExp solution is perfectly alright!

I try to match/get all repetitions in a string. This is what I've done so far:

var str = 'abcabc123123';
var REPEATED_CHARS_REGEX = /(.).*\1/gi;

console.log( str.match(REPEATED_CHARS_REGEX) ); // => ['abca', '1231']

As you can see the matching result is ['abca', '1231'], but I excpect to get ['abc', '123']. Any ideas to acplish that?

2nd question:

Another thing I excpect, is to make it possible to change the duration how often a char needs to be in the string to get matched...

For example if the string is abcabcabc and the repetation-time is set to 2 it should result in ['abcabc']. If set to 3 it should be ['abc'].

Update

A non-RegExp solution is perfectly alright!

Share Improve this question edited Aug 11, 2013 at 10:40 yckart asked Aug 11, 2013 at 10:25 yckartyckart 33.5k9 gold badges126 silver badges133 bronze badges 3
  • What do you expect with the string: abc123ab12? – Toto Commented Aug 11, 2013 at 10:31
  • @M42 Mhh, ['ab', '12']... – yckart Commented Aug 11, 2013 at 10:32
  • The reason you're getting 'abca' and '1231' is that your regex matches any one character (.) followed by any number of other characters .* followed by whatever the first character was \1. You need to change the part in the parentheses to match all of the first group of letters. – nnnnnn Commented Aug 11, 2013 at 11:02
Add a ment  | 

4 Answers 4

Reset to default 5

Well, I think falsetru had a good idea with a zero-width look-ahead.

'abcabc123123'.match(/(.+)(?=\1)/g)
// ["abc", "123"]

This allows it to match just the initial substring while ensuring at least 1 repetition follows.

For M42's follow-up example, it could be modified with a .*? to allow for gaps between repetitions.

'abc123ab12'.match(/(.+)(?=.*?\1)/g)
// ["ab", "12"]

Then, to find where the repetition starts with multiple uses together, a quantifier ({n}) can be added for the capture group:

'abcabc1234abc'.match(/(.+){2}(?=.*?\1)/g)
// ["abcabc"]

Or, to match just the initial with a number of repetitions following, add the quantifier within the look-ahead.

'abc123ab12ab'.match(/(.+)(?=(.*?\1){2})/g)
// ["ab"]

It can also match a minimum number of repetitions with a range quantifier without a max -- {2,}

'abcd1234ab12cd34bcd234'.match(/(.+)(?=(.*?\1){2,})/g)
// ["b", "cd", "2", "34"]

This solution may be used if you don't want to use regex:

function test() {
    var stringToTest = 'find the first duplicate character in the string';
    var a = stringToTest.split('');
    for (var i=0; i<a.length; i++) {
        var letterToCompare = a[i];
        for (var j=i+1; j<a.length; j++) {
            if (letterToCompare == a[j]) {
                console.log('first Duplicate found');
                console.log(letterToCompare);
                return false;
            }
        }
    }
}
test()

The answer above returns more duplicates than there actually are. The second for loop causes the problem and is unnecessary. Try this:

function stringParse(string){
  var arr = string.split("");
  for(var i = 0; i<arr.length; i++){
    var letterToCompare = arr[i];
    var j= i+1;
    if(letterToCompare === arr[j]){
      console.log('duplicate found');
      console.log(letterToCompare);
    }    
  }  
}
var duplicateCheck = function(stru) {
    var flag = false;
    for (let o = 0; o < stru.length; o++) {
        for (let p = 0; p < stru.length; p++) {
            if (stru.charAt(o) === stru.charAt(p) && o!==p) {
                flag = true;
                break;
            }
        }
    }
    
    return flag;
}

true ==> duplicate found

本文标签: javascriptGet duplicate characters in stringStack Overflow