Website hosting service by Active-Venture.com
  

 Back to Index

Matching this or that

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.

 

 

 

Domain name registration service & domain search - 
Register cheap domain name from $7.95 and enjoy free domain services 
 

Cheap domain name search service -
Domain name services at just
$8.95/year only
 

Register domain name -
Buy domain name registration and cheap domain transfer at low, affordable price.

© 2002-2004 Active-Venture.com Web Site Hosting Service

 

[ A printer consists of three main parts: the case, the jammed paper tray and the blinking red light.   ]

 

 
 
 

Disclaimer: This documentation is provided only for the benefits of our web hosting customers.
For authoritative source of the documentation, please refer to http://www.perldoc.com