4

I'm trying to find multiple consecutive digits through regex in javascript

Let's say I've got:

12345abc123

I want to know how many times I've got 3 or more consecutive digits. Right now I'm using:

/\d{3}/g

But that gives me: 123, 123 and I want to have: 123, 234, 345, 123

How can I change my regex to get want I want?

subarroca
  • 851
  • 7
  • 22

3 Answers3

8

You can use this regex:

/(?=(\d{3}))/g

Online Regex Demo

Code:

var re = /(?=(\d{3}))/g; 
var str = '12345abc789';
var m;
while ((m = re.exec(str)) != null) {
    console.log(m[1]);
}

Output:

123
234
345
789
anubhava
  • 761,203
  • 64
  • 569
  • 643
4

You'd have to use look-ahead assertions:

var str = '12345abc123', 
re = /\d(?=(\d\d))/g;

while ((match = re.exec(str)) !== null) {
    // each match is an array comprising
    // - the first digit and
    // - the next two digits
    console.log(match.join(''));
}

It matches a digit if followed by another two; the assertion causes the engine to start the next search right after the first matched digit.

Ja͢ck
  • 170,779
  • 38
  • 263
  • 309
1

This is the regex you are looking for:

/(?=(\d{3}))/g
North
  • 90
  • 4