Basic HTML version of Foils prepared March 30 97

Foil 41 Parentheses in Regular Expressions
(Chapter 7 of the Llama Book)

From PERL4 Tutorial for CPS616 Computational Science for Information Age Course CPS616 -- February 1995. by Geoffrey C. Fox


Parentheses can be used as "memory" for relating different parts of a match or for relating substitution to match
If a part of a regular expression is enclosed in parentheses, the MATCHED value is stored in temporary variables \1 \2 .. for first,second .. set of parentheses
  • /Geoffrey(.*)Fox/ when matched to Geoffrey Charles Fox stores
  • \1 = ' Charles ' which can be transferred to substitution string which could be
  • /Geoffrey \(\1\) Fox/ for result Geoffrey ( Charles ) Fox
  • Note ONLY use \1 \2 etc. in pattern. Use $1 $2 outside pattern
Parentheses can also be used to clarify meaning of a regular expression by defining precedence of a set of operations and so distinguish for instance
  • /(a|b)*/ from /a|(b*)/
  • There is a definite convention for precendence but as usual I recommend using parantheses and in Perl5(later) we will see how to distinguish use of parantheses for either clarificatiuon or defining matched groups.



© 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 Sat Sep 6 1997