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?
You can use this regex:
/(?=(\d{3}))/g
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With