0

Is there any way in js to use RegExp and str.match() to count combinations of substrings in a string? I'm trying to achieve the following:

given a string:

'999999000'

I need to find all the combination of 99 that exist in the string, the expected result for the above string is 5 as you can combine the indexes in the following pairs to create a 99:

index 0 and 1
index 1 and 2
index 2 and 3
index 3 and 4
index 4 and 5

now I've tried using the match method the following way:

    let re = new RegExp("99","gi");
    let matches = "999999000".match(re).length;
    console.log(matches);

but the result it throws it's 3.

note that the above snippet would work for the following case:

    let re = new RegExp("99","gi");
    let matches = "00990099099099".match(re).length;
    console.log(matches);

I know this problem can be solved by iterating on the string to find all the'99' combinations, but I want to solve it using regex and str.match

BuddyEorl
  • 64
  • 6

1 Answers1

3

You could use a positive lookahead to assert 2 times a 9:

(?=(9{2}))

const strings = [
  "999999000",
  "00990099099099"
];
let re = new RegExp("(?=(9{2}))", "gi");
strings.forEach((s) => {
  console.log(s + " ==> " + s.match(re).length);
});
The fourth bird
  • 154,723
  • 16
  • 55
  • 70
  • now that solves the problem for that specific case, how can i use a variable in the regExp object for example instead of '99' i have the substring stored in a variable X ? – BuddyEorl Jul 29 '18 at 08:52
  • 1
    For this example you could use the RegExp constructor and pass your variable `new RegExp("(?=(" + variable + "{2}))","gi");` . I think [this page](https://stackoverflow.com/questions/17885855/use-dynamic-variable-string-as-regex-pattern-in-javascript/17886301) can be helpful about escaping what you pass as a variable. – The fourth bird Jul 29 '18 at 09:10
  • thanks, I used your answer to solve my problem, your answer worked for me only when the substring was length 2, but would fail for other cases, I end up doing the following: `let P= "099990999099990909099"; let test= "(?=("+P+"{1}))" let re = new RegExp(test,"gi"); let matches = arrayG.match(re).length;` – BuddyEorl Jul 29 '18 at 09:17