const regex = /P(ost)?[\.\s]*(O|0)(ff(ice)?)?[\.\s]+B(o|0)x/gmi;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('P(ost)?[\\.\\s]*(O|0)(ff(ice)?)?[\\.\\s]+B(o|0)x', 'gmi')
const str = `PO Box
P.O. Box
PO. Box
po box
P.o box
PoBox
p.o. Box
post office box 716
Post O. box
Post off box
p office box
p off BOX
p0 box
p0ffice box k`;
// 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