| ACADEMIC COMPUTING and COMMUNICATIONS CENTER | ||||||||
| ||||||||||||||||||||||||||||||||||||
Regular Expressions | ||||||||||||||||||||||||||||||||||||
| Elements | ||||||||||||||||||||||||||||||||||||
|
This table is incomplete, but contains a few more regexp goodies.
Modifiers come after the regular expression, and modify its behaviour. The following list is incomplete.
|
||||||||||||||||||||||||||||||||||||
| More examples | ||||||||||||||||||||||||||||||||||||
|
$s = '<a href="basil" > and <a Href=thyme>';
$s =~ /(<.*>)/; # greedy - from first < to last >
$s =~ /(<.*?>)/; # not greedy - from first < to first >
$s =~ /href=(.*?)[ >]/; # "basil"
@a = ($s =~ /href=(.*?)[ >]/); # ("basil")
@a = ($s =~ /href=(.*?)[ >]/g); # ("basil")
@a = ($s =~ /href=(.*?)[ >]/ig); # ("basil", thyme)
|
||||||||||||||||||||||||||||||||||||
| Interpolation | ||||||||||||||||||||||||||||||||||||
|
A regular expresion will interpolate perl variables just as in double quotes. The interpolation happens before the regexp is compiled. This feature lets you determin the regular expression at runtime. $pat = "def"; $string =~ /abc|$pat*/; $string =~ /abc|def*/; same thing $string =~ /abc|(def)*/; not same thing |
||||||||||||||||||||||||||||||||||||
| Backreferences | ||||||||||||||||||||||||||||||||||||
|
Parentheses are used for memory, as well as grouping. But you can use this memory in the match pattern. Use \1, \2, and so on to refer to what was matched by the various sets of parentheses. If you want to match a word that has a repeated vowel, ( such as reed, but not read ):
$string =~ /([aeiou])\1/; # Look for repeated vowel
|
||||||||||||||||||||||||||||||||||||
| Perl II | Previous: 4. Subroutines | Next: 6. Ties & DBM |
| 1999-4-6 BobG |
|