How can I make the Perl regex part optional?

I want a match

 my @array = ( 'Tree' , 'JoeTree');

    foreach (@array ) {
      if ( $_ =~ /^(Joe)Tree/gi) {
        print "matched $_";
      }
    }

This only matches JoeTree. Does this not match the tree?

+3
source share
2 answers

Try:

if (/^(?:Joe)?Tree/gi)
  • We have added a part Joe.
  • You can also change (..)to (?:...)because you are just grouping.
  • Also, the part $_ =~is redundant, since by default we check$_
+10
source

You missed ?:/^(Joe)?Tree/gi

+5
source

Source: https://habr.com/ru/post/1765796/


All Articles