User Guide

Regular expression syntax 297
Using groups to capture substring matches
When you define a standard parenthetical group in a pattern, you can later refer to it in the
regular expression. This is known as a backreference, and these sorts of groups are known as
capturing groups. For example, in the following regular expression, the sequence
\1 matches
whatever substring matched the capturing parenthetical group:
var pattern:RegExp = /(\d+)-by-\1/;
// matches the following: 48-by-48
You can specify up to 99 of these backreferences in a regular expression by typing
\1, \2, ... , \99.
Similarly, in the
replace() method of the String class, you can use $1–$99 to insert captured
group substring matches in the replacement string:
var pattern:RegExp = /Hi, (\w+)\./;
var str:String = "Hi, Bob.";
trace(str.replace(pattern, "$1, hello."));
// output: Bob, hello.
Also, if you use capturing groups, the exec() method of the RegExp class and the match()
method of the String class return substrings that match the capturing groups:
var pattern:RegExp = /(\w+)@(\w+).(\w+)/;
var str:String = "bob@example.com";
trace(pattern.exec(str));
// bob@test.com,bob,example,com
Using noncapturing groups and lookahead groups
A noncapturing group is one that is used for grouping only; it is not “collected,” and it does
not match numbered backreferences. Use
(?: and ) to define noncapturing groups, as
follows:
var pattern = /(?:com|org|net);
For example, note the difference between putting (com|org) in a capturing versus a
noncapturing group (the
exec() method lists capturing groups after the complete match):
var pattern:RegExp = /(\w+)@(\w+).(com|org)/;
var str:String = "bob@example.com";
trace(pattern.exec(str));
// bob@test.com,bob,example,com
//noncapturing:
var pattern:RegExp = /(\w+)@(\w+).(?:com|org)/;
var str:String = "bob@example.com";
trace(pattern.exec(str));
// bob@test.com,bob,example