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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With