const regex = /(?(DEFINE)(?<cons>\b(?:
(?<x>\d*)
(?:(?<a0>0)|(?<a1>1)|(?<a2>2)|(?<a3>3)|(?<a4>4)
|(?<a5>5)|(?<a6>6)|(?<a7>7)|(?<a8>8))
(?:9(?= 9*,\g{x}\d (?<y>\g{y}?+ 0)))*
,\g{x}
(?(a0)1)(?(a1)2)(?(a2)3)(?(a3)4)(?(a4)5)
(?(a5)6)(?(a6)7)(?(a7)8)(?(a8)9)
(?(y)\g{y})
# handle the 999 => 1000 case separately
| (?:9(?= 9*,1 (?<z>\g{z}?+ 0)))+
,1\g{z}
)\b))
# list of two or more consecutive integers
(?=(?&cons))\d+
(?:,(?=(?&cons))\d+)*
,\d+/g;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?(DEFINE)(?<cons>\\b(?:
(?<x>\\d*)
(?:(?<a0>0)|(?<a1>1)|(?<a2>2)|(?<a3>3)|(?<a4>4)
|(?<a5>5)|(?<a6>6)|(?<a7>7)|(?<a8>8))
(?:9(?= 9*,\\g{x}\\d (?<y>\\g{y}?+ 0)))*
,\\g{x}
(?(a0)1)(?(a1)2)(?(a2)3)(?(a3)4)(?(a4)5)
(?(a5)6)(?(a6)7)(?(a7)8)(?(a8)9)
(?(y)\\g{y})
# handle the 999 => 1000 case separately
| (?:9(?= 9*,1 (?<z>\\g{z}?+ 0)))+
,1\\g{z}
)\\b))
# list of two or more consecutive integers
(?=(?&cons))\\d+
(?:,(?=(?&cons))\\d+)*
,\\d+', 'g')
const str = `0,1,2,3
8,9,10,11
1999,2000,2001
99,100,101
42
3,2,1
1,2,4
10,11,13`;
// Reset `lastIndex` if this regex is defined globally
// regex.lastIndex = 0;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for JavaScript, please visit: https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions