|
Sometimes we would like to our regexp to be able to match different possible words or
character strings. This is accomplished by using the alternation metacharacter |.
To match dog or cat, we form the regexp dog|cat. As
before, perl will try to match the regexp at the earliest possible point in the string. At each
character position, perl will first try to match the first alternative, dog. If dog
doesn't match, perl will then try the next alternative, cat. If cat
doesn't match either, then the match fails and perl moves to the next position in the string.
Some examples:
"cats and dogs" =~ /cat|dog|bird/; # matches "cat"
"cats and dogs" =~ /dog|cat|bird/; # matches "cat"
|
|
Even though dog is the first alternative in the second regexp, cat
is able to match earlier in the string.
"cats" =~ /c|ca|cat|cats/; # matches "c"
"cats" =~ /cats|cat|ca|c/; # matches "cats"
|
|
Here, all the alternatives match at the first string position, so the first alternative is
the one that matches. If some of the alternatives are truncations of the others, put the longest
ones first to give them a chance to match.
"cab" =~ /a|b|c/ # matches "c"
# /a|b|c/ == /[abc]/
|
|
The last example points out that character classes are like alternations of characters. At a
given character position, the first alternative that allows the regexp match to succeed will be
the one that matches.
|
|