开发者

How can I make part of a Perl regular expression optional? [duplicate]

This question already has answers here: How can I make part of regex optional? (2 answers) Closed 3 months a开发者_JS百科go.

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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜