Perl Regular Expressions Part IIGroupingExtracting MatchesBackreferencesRegex Result VariablesQuantifying MetacharactersQuantifying Metacharacters continued…Greedy QuantifiersNon-Greedy QuantifiersMichael KovalchikCS 265, Fall 2009Parenthesis group parts of expressions together“/CS265|CS270/” => “/CS(265|270)/”Groups can be nested“/Perl|Pearl/” => “/P(e(a|))rl/”Parenthesis also serve to extract the matched stringsabcde matched with “/(abc)(de)/” will match the string and store ‘abc’ in the variable $1 and ‘de’ in $2Backreferences 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 copiesThe 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 matchUsing $`, $’ and to a lesser extent $& slows regular expression processing? – 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’){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)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- ‘’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
View Full Document