const regex = /^
(?<batch_number>\d{2})-
(?:
(?<component>QQ|CO|CG)
(?<target_group>[AS])
(?<paper>P)?
)
(?:-
(?<domain>(?:LDW|MAT|REA|SCI|XYZ)
(?<division>[abc])?
)
)?
-(?<authoring_point>[TN])
$/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^
(?<batch_number>\\d{2})-
(?:
(?<component>QQ|CO|CG)
(?<target_group>[AS])
(?<paper>P)?
)
(?:-
(?<domain>(?:LDW|MAT|REA|SCI|XYZ)
(?<division>[abc])?
)
)?
-(?<authoring_point>[TN])
$', 'gm')
const str = `01-COS-SCIa-N
02-COS-SCIb-N
03-COS-SCIc-N
04-QQS-N
05-QQA-N
06-COS-LDW-N
07-COS-XYZ-N
08-CGA-SCI-N
11-COS-MATa-T
12-COS-MATb-T
13-COS-REAa-T
14-COS-REAb-T
15-COS-SCIa-T
16-COS-SCIb-T
17-CGA-SCI-T
18-CGA-MAT-T
19-CGA-REA-T
21-COSP-REAa-T
22-COSP-REAb-T
23-COSP-MATa-T
24-COSP-MATb-T
25-COSP-SCIa-N
26-COSP-SCIa-T
27-QQSP-N
28-QQAP-N
29-COSP-XYZ-N
`;
// 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