ACCC Home Page ACADEMIC COMPUTING and COMMUNICATIONS CENTER
Accounts / Passwords Email Labs / Classrooms Telecom Software Computing and Network Services Education / Teaching Getting Help
 
Seminar - Perl II
0. Contents 1. Intro 2. Sources 3. Special Variables 4. Subroutines 5. Regexp
6. Ties & DBM 7. Functions 8. Eval 9. Larger Example 10. Exercises  

Regular Expressions

   
 
     
Elements
 

This table is incomplete, but contains a few more regexp goodies.
atom meaning
lookahead assertions
(?=...) match if (...) would match next
(?!...) match if (...) would not match next
Repeats
{m} exactly m times
{m,n} from m to n times
Greed
? not greedy
Memory
(?: ...) grouping, no memory

Modifiers come after the regular expression, and modify its behaviour. The following list is incomplete.
ModifierBehavior
/i case insensitive
/g global - all matches
/o compile pattern once
/s multi-lines as single string
/x allow whitespace and comments

 
     
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
UIC Home Page Search UIC Pages Contact UIC