Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do both alternatives match when using | in Perl regular expressions?

Tags:

regex

perl

I am confused about the regular expression below. Please help me to understand it.

my $test = "fred andor berry";
if ($test =~ /fred (and|or) berry/) {
    print "Matched!\n";
} else {
      print "Did not match!\n";
}

I thought it would match, but I get "Did not match!". If I add + in it, like this,

my $test = "fred andor berry";
if ($test =~ /fred (and|or)+ berry/) {
   print "Matched!\n";
} else {
   print "Did not match!\n";
}

Then it matches. I thought I can use and|or to match an expression with "and", "or" and "andor". No?

like image 593
Elie Xu Avatar asked Nov 28 '22 17:11

Elie Xu


1 Answers

The part of the regex that is (and|or) means match 'and' or 'or' but not both. When you append the plus to that group it can then match one or more times. For example "fred andandand berry" would also be a valid match for /fred (and|or)+ berry/

like image 62
cftarnas Avatar answered Dec 06 '22 07:12

cftarnas