const regex = /^[A-Z0-9]+(?:-[A-Z0-9]+)?(?:,[A-Z0-9]+(?:-[A-Z0-9]+)?)*$/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^[A-Z0-9]+(?:-[A-Z0-9]+)?(?:,[A-Z0-9]+(?:-[A-Z0-9]+)?)*$', 'gm')
const str = `//Valid Values
D1
DF2,AB2
D1-2
A1, A2
D1 - 2
1 - FH15
1-R3
1,D2
1,H5,8,S4
1 , H5, 8, S4
1, D2, D6-8, 6-9
1,D2,D6-8,6-9,G2,8
1-D3,TT6-8
1-D3, TT6-8
1-3, VB8, 11-SD13, R15
//Invalid values
1*, 3
,1,F2
-1-TG3
12-D4,
D1-F2-
1- F2- 4
D10,/
1234s
F4-,8
4,-H5
D3-F-G7
D3 - F - G7
4 , - H5
1*,D
12 - D4`;
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