User Guide
298 Using Regular Expressions
A special type of noncapturing group is the lookahead group, of which there are two types: the
positive lookahead group and the negative lookahead group.
Use
(?= and ) to define a positive lookahead group, which specifies that the subpattern in the
group must match at the position. However, the portion of the string that matches the
positive lookahead group can match remaining patterns in the regular expression. For
example, because
(?=e) is a positive lookahead group in the following code, the character e
that it matches can be matched by a subsequent part of the regular expression—in this case,
the capturing group,
\w*):
var pattern:RegExp = /sh(?=e)(\w*)/i;
var str:String = "Shelly sells seashells by the seashore";
trace(pattern.exec(str));
// Shelly,elly
Use (?! and ) to define a negative lookahead group that specifies that the subpattern in the
group must not match at the position. For example:
var pattern:RegExp = /sh(?!e)(\w*)/i;
var str:String = "She sells seashells by the seashore";
trace(pattern.exec(str));
// shore,ore
Using named groups
A named group is a type of group in a regular expression that is given a named identifier. Use
(?P<name> and ) to define the named group. For example, the following regular expression
includes a named group with the identifier named
digits:
var pattern = /[a-z]+(?P<digits>\d+)[a-z]+/;
When you use the exec() method, a matching named group is added as a property of the
result array:
var myPattern:RegExp = /([a-z]+)(?P<digits>\d+)[a-z]+/;
var str:String = "a123bcd";
var result:Array = myPattern.exec(str);
trace(result.digits); // 123
Here is another example, which uses two named groups, with the identifiers name and dom:
var emailPattern:RegExp =
/(?P<name>(\w|[_.\-])+)@(?P<dom>((\w|-)+))+\.\w{2,4}+/;
var address:String = "bob@example.com";
var result:Array = emailPattern.exec(address);
trace(result.name); // bob
trace(result.dom); // example
NOTE
Named groups are not part of the ECMAScript language specification. They are an
added feature in ActionScript 3.0.