Basic HTML version of Foils prepared 3 March 99

Foil 71 Parentheses in Regular Expressions

From Overview of JavaScript I -- Basic Web Scripting Language CPS616 Technologies of the Information Age -- Spring Semester 99. by Geoffrey C. Fox (Tom Scavo)


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
  • /apple(,)\sorange\1/ matches apple, orange, in apple, orange, cherry, peach.
  • Note ONLY use \1 \2 etc. in pattern. Use $1 $2 (static properties of RegExp object) outside pattern
  • re1= /Geoffrey(.*)Fox/ when matched to str = "Geoffrey Charles Fox" stores
  • \1 = ' Charles ' which can be transferred to substitution string (via newstr = str.replace(re1,re2);) which could be
  • re2 = /Geoffrey \($1\) Fox/ for result Geoffrey ( Charles ) Fox
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 precedence, but as usual I recommend using parentheses



© 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 Wed Mar 3 1999