Regular Expressions   «Prev 

Pattern Modifiers

All regular expression operators support a number of pattern modifiers. These change the way in which the expression is interpreted. Before we look at the specifics of the individual regular expression operators, we will look at the common pattern modifiers that are shared by all the operators.
Pattern modifiers are a list of options placed after the final delimiter in a regular expression and that modify the method and interpretation applied to the searching mechanism. Perl supports five basic modifiers that apply to the m//, s///, and qr// operators, as listed here in the Table 4-5. You place the modifier after the last delimiter in the expression.
For example m/foo/i. The /i modifier tells the regular expression engine to ignore the case of supplied characters so that /cat/ would also match CAT, cAt, and Cat.
The /s modifier tells the regular expression engine to allow the . metacharacter to match a newline character when used to match against a multiline string. The /m modifier tells the regular expression engine to let the ^ and $ metacharacters to match the beginning and end of a line within amultiline string.
This means that /^The/ will match "Dog\nThe cat".
The normal behavior would cause this match to fail, because ordinarily the ^ operator matches only against the beginning of the string supplied.

Perl Regular Expression Modifiers for Matching and Substitution
Table 4-5: Perl Regular Expression Modifiers for Matching and Substitution

Perl Pattern Matching Modifiers

The following code example contains a simple Perl script that will take a file with a list of unorganized names and print out all the names that begin with the letter g.

while(<>) {
  @tags = /\b(g\w+)/ig;
  foreach (@tags) { print "$_\n" }
}

while (<>): This is shorthand for while(<STDIN>). In other words, do this while there is input from the keyboard.
  1. @tags =: Put whatever items are on the right of the operator into an array named @tags.
  2. \b: Match on the word boundry, i.e., match whole words.
  3. (g\w+): Match all words beginning with g.
  4. ig: Ignore case and apply to all matches within the string.