Download presentation
Presentation is loading. Please wait.
Published byNelson Sullivan Modified over 9 years ago
1
Michael Kovalchik CS 265, Fall 2009
2
Parenthesis group parts of expressions together “/CS265|CS270/” => “/CS(265|270)/” Groups can be nested “/Perl|Pearl/” => “/P(e(a|))rl/”
3
Parenthesis also serve to extract the matched strings abcde matched with “/(abc)(de)/” will match the string and store ‘abc’ in the variable $1 and ‘de’ in $2
4
Backreferences find earlier matches later in the string /1 is to match the group in $1, /2 in $2, etc. “/^(\w\w\w)\s\1$/” matches when a three letter word is duplicated with a space between the copies
5
The results of a regular expression search are stored in special variables. ◦ $` (tilde) is set to the part of the string before a match ◦ $& is set to the part of the string that matched the expression ◦ $’ (single quote) is set to the part of the string after a match Using $`, $’ and to a lesser extent $& slows regular expression processing
6
? – Matches the preceding 1 or 0 times ◦ a? = match the character ‘a’ 1 or 0 times. (‘a’ or ‘’) + - Matches the preceding 1 or more times ◦ a+ = match ‘a’ atleast once. (‘a’ and ‘aaaa’) * - Matches the preceding 0 or more times ◦ a* = match ’a’ any number of times. (‘’, ‘a’, ‘aaaa’)
7
{n,m} – Matches atleast n, but less than m times. ◦ a{2,4} = match ‘a’ atleast 2, no more than 4 times. (‘aa’ and ‘aaaa’, but not ‘a’ or ‘aaaaa’) {n,} – Match atleast n times. ◦ a{3,} = match ‘a’ atleast 3 times. (‘aaa’ and ‘aaaaa’, but not ‘a’ or ‘aa’) {n} – match exactly n times. ◦ a{2} = match ‘a’ exactly 2 times. (‘aa’ only)
8
Perl Quantifiers will match the longest string possible “the cat in the hat” =~ /^(.*)(cat)(.*)$/ ◦ $1- ‘the ’ ◦ $2- ‘cat’ ◦ $3- ‘ in the hat’ “the cat in the hat =~ /^(.*)(at)(.*)$/ ◦ $1- ‘the cat in the h’ ◦ $2- ‘at’ ◦ $3- ‘’
9
To have a quantifier match the smallest possible string append a ‘?’ to them. ◦ Examples: ??, *?, +? {n,m}? “the cat in the hat =~ /^(.*?)(at)(.*?)$/ ◦ $1- ‘the c ’ ◦ $2- ‘at’ ◦ $3- ‘ in the hat’
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.