use strict;
my $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';
my $regex = qr/(?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+/mp;
if ( $str =~ /$regex/g ) {
print "Whole match is ${^MATCH} and its start/end positions can be obtained via \$-[0] and \$+[0]\n";
# print "Capture Group 1 is $1 and its start/end positions can be obtained via \$-[1] and \$+[1]\n";
# print "Capture Group 2 is $2 ... and so on\n";
}
# ${^POSTMATCH} and ${^PREMATCH} are also available with the use of '/p'
# Named capture groups can be called via $+{name}
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 Perl, please visit: http://perldoc.perl.org/perlre.html