Basic HTML version of Foils prepared Sept 20 97

Foil 42 Parentheses in Regular Expressions

From Tutorial on PERL Computational Science for Information Age Course CPS616 -- Sept 20 97. by Geoffrey C. Fox,Nancy McCracken,Tom Scavo


Parentheses can be used as "memory" for relating different parts of a match or for substitution
If subexpressions are enclosed in parentheses, the matched values are put in temporary variables \1, \2, etc.
  • s/Geoffrey(.*)Fox/Geoffrey \(\1\) Fox/
  • when matched to 'Geoffrey Charles Fox' stores \1 = ' Charles ', which is transferred to substitution string giving result 'Geoffrey ( Charles ) Fox'
  • Note: Use \1, \2, etc. inside pattern only; use $1, $2, etc. outside pattern
Parentheses are also used to clarify the meaning of a regular expression. For instance,
  • /(a|b)*/ is different than /a|(b*)/
In regular expressions, variables are interpolated as in double-quoted strings. Use \$ to represent a literal dollar sign except at end of string where it represents end-of-string anchor.



© Northeast Parallel Architectures Center, Syracuse University, npac@npac.syr.edu

If you have any comments about this server, send e-mail to webmaster@npac.syr.edu.

Page produced by wwwfoil on Sun Sep 21 1997