contents   index   previous   next



RegExp exec()

syntax:

regexp.exec([str])

where:

str - a string on which to perform a regular expression match. Default is RegExp.input.

 

return:

array - an array with various elements and properties set depending on the attributes of a regular expression. Returns null if no match is found.

 

description:

This method, of all the RegExp and String methods, is both the most powerful and most complex. For many, probably most, searches, other methods are quicker and easier to use. A string, the target, to be searched is passed to exec() as a parameter. If no string is passed, then RegExp.input, which is a read/write property, is used as the target string.

 

When executed without the global attribute, "g", being set, if a match is found, element 0 of the returned array is the text matched, element 1 is the text matched by the first sub pattern in parentheses, element 2 the text matched by the second sub pattern in parentheses, and so forth. These elements and their numbers correspond to groups in regular expression patterns and replacement expressions. The length property indicates how many text matches are in the returned array. In addition, the returned array has the index and input properties. The index property has the start position of the first text matched, and the input property has the target string that was searched. These two properties are the same as those that are part of the returned array from String match() when used without its global attribute being set.

 

When executed with the global attribute being set, the same results as above are returned, but the behavior is more complex which allows further operations. This method exec() begins searching at the position, in the target string, specified by this.lastIndex. After a match, this.lastIndex is set to the position after the last character in the text matched. Thus, you can easily loop through a string and find all matches of a pattern in it. The property this.lastIndex is read/write and may be set at anytime. When no more matches are found, this.lastIndex is reset to 0.

 

Since RegExp exec() always includes all information about a match in its returned array, it is the best, perhaps only, way to get all information about all matches in a string.

 

As with String match(), if any matches are made, appropriate RegExp object static properties, such as RegExp.leftContext, RegExp.rightContext, RegExp.$n, and so forth are set, providing more information about the matches.

 

see:

String match(), RegExp object static properties

 

example:

var str = "one two three tio one";

var pat = new RegExp("t.o", "g");

 

while ((rtn = pat.exec(str)) != null)

   Screen.writeln("Text = " + rtn[0] + 

                  " Pos = " + rtn.index +

                  " End = " + pat.lastIndex);

// Display is:

//  Text = two Pos = 4 End = 7

//  Text = tio Pos = 14 End = 17

 


RegExp test()