How can I make part of a Perl regular expression optional? [duplicate]
I want match
my @array = ( 'Tree' , 'JoeTree');
foreach (@array ) {
if ( $_ =~ /^(Joe)Tree/gi) {
print "matched $_";
}
}
It matching only JoeTree. It's not matching Tree ?
Try:
if (/^(?:Joe)?Tree/gi)
- We've made the
Joe
part optional. - Also you can change
(..)
to(?:...)
as you are just grouping. - Also
$_ =~
part is redundant as by default we check in$_
You missed a ?
: /^(Joe)?Tree/gi
精彩评论