const regex = /^(([A-Z][A-HJ-Y]?\d[A-Z\d]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?\d[A-Z]{2}|BFPO ?\d{1,4}|(KY\d|MSR|VG|AI)[ -]?\d{4}|[A-Z]{2} ?\d{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$/gmi;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('^(([A-Z][A-HJ-Y]?\\d[A-Z\\d]?|ASCN|STHL|TDCU|BBND|[BFS]IQQ|PCRN|TKCA) ?\\d[A-Z]{2}|BFPO ?\\d{1,4}|(KY\\d|MSR|VG|AI)[ -]?\\d{4}|[A-Z]{2} ?\\d{2}|GE ?CX|GIR ?0A{2}|SAN ?TA1)$', 'gmi')
const str = `AI-1111
ASCN 1ZZ
STHL 1ZZ
TDCU 1ZZ
BBND 1ZZ
BIQQ 1ZZ
FIQQ 1ZZ
GX11 1ZZ
PCRN 1ZZ
SIQQ 1ZZ
TKCA 1ZZ
BFPO 11
ZZ 11
GE CX
KY1-1111
VG1111
MSR 1111
A1A 1AA
A1 1AA
A11 1AA
AA1 1AA
AA1A 1AA
AA11 1AA
A1A1AA
A11AA
A111AA
AA11AA
AA1A1AA
AA111AA
GIR 0AA
GIR0AA
BFPO 1
BFPO 11
BFPO 111
BFPO 1111
SAN TA1`;
// 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