const regex = /^\s*\d+(?:\s*-\s*\d+\s*)?(?:\s*,\s*\d+(?:\s*-\s*\d+)?)*\s*$/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^\\s*\\d+(?:\\s*-\\s*\\d+\\s*)?(?:\\s*,\\s*\\d+(?:\\s*-\\s*\\d+)?)*\\s*$', 'gm')
const str = `Valid ones
64344
9434
434-543
434-543
434 - 543
4435 - 343434
1-2,3,5,6
1-2,3,5,6-6,45-4
3,5,6, 8 - 9,24
1-2,3,5 ,6
1- 2,3, 5,6-6,45-4
Invalid ones
23 -
2343.3434
343.3434 - 13.466
23 ,
234,
,54
xyz 9
3,5,6,8-9,24,
,35,65,65
,35,65,65 -
,3 5,65,65,
3,5,6, 8- 9,24,
1- 2,3, 5,6-6,4 5-4
, 35,65,6 5
,35, 6 5,65,`;
// 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