Parentheses in Regular Expressions
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