const regex = /(?i)^\s*(.*((p|post)[-.\s]*(o|off|office)[-.\s]*(b|box|bin)[-.\s]*)|.*((p|post)[-.\s]*(o|off|office)[-.\s]*)|.*((p|post)[-.\s]*(b|box|bin)[-.\s]*)|(box|bin)[-.\s]*)(#|n|num|number)?\s*\d+/gm;
// Alternative syntax using RegExp constructor
// const regex = new RegExp('(?i)^\\s*(.*((p|post)[-.\\s]*(o|off|office)[-.\\s]*(b|box|bin)[-.\\s]*)|.*((p|post)[-.\\s]*(o|off|office)[-.\\s]*)|.*((p|post)[-.\\s]*(b|box|bin)[-.\\s]*)|(box|bin)[-.\\s]*)(#|n|num|number)?\\s*\\d+', 'gm')
const str = `-- Match
post office box 1
post office bin 1
post office b 1
post off box 1
post off bin 1
post off b 1
post o box 1
post o bin 1
post o b 1
p office box 1
p office bin 1
p office b 1
p off box 1
p off bin 1
p off b 1
p o box 1
p o bin 1
p o b 1
p-o-b-1
p.o.b.1
POB1
pob1
pob#1
pob #1
pob # 1
p o b # 1 x
p o b # 1 x
pob n1
pob num1
pob number1
foo pob1
1 pob1
box 1
bin 1
box-1
box.1
box1
BOX1
box#1
box #1
box # 1
box # 1 x
box # 1 x
po 1
po n1
PO 1
pb 1
pb n1
PB 1
-- No Match
foo box 1
b1
#1
1 box 1
1 pob
post 1
n1
number1
num1
post office box
post office bin
post office b
post off box
post off bin
post off b
post o box
post o bin
post o b
p office box
p office bin
p office b
p off box
p off bin
p off b
p o box
p o bin
p o b
p-o-b-
p.o.b.
POB
pob
pob#
pob #
pob #
p o b # x
p o b # x
pob n
pob num
pob number
foo pob
box
bin
box-
box.
box
BOX
box#
box #
box #
box # x
box # x
po
po n
PO
pb
pb n
PB`;
// 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