Java Reference
In-Depth Information
The exec() method searches the input text against the pattern and returns null or
an Array object. When a match is not found, it returns null . When a match is found, the
returned Array object has the following pieces of information:
The first element of the array is the matched text of the input text.
Subsequent elements in the array, if any, are the matched text by
the capturing parentheses in the pattern. (I will discuss capturing
parentheses later in this chapter.)
index property that is set to position where the
The array has an
match started.
input property that is set to the input text.
The array has an
g ), the lastIndex property of
the RegExp object is set to position in the input text immediately
following the matched text. If, for a global search, a match is not
found, the lastIndex property of the RegExp object is set to zero.
For a nonglobal match, the lastIndex property is untouched.
Notice that the exec() method starts the search from the position defined by the
lastIndex property of the RegExp object. If you are performing a global search, you can
use a loop to find all matches in the input text. Listing 4-25 demonstrates how to use the
exec() method.
If the search is global (using the flag
Listing 4-25. Using the exec() Method of the RegExp Object for a Global Match
// regexexec.js
var pattern = /Java/g;
var text = "Java and JavaScript are not the same";
var result;
while((result = pattern.exec(text)) !== null) {
var msg = "Matched '" + result[0] + "'" + " at " + result.index +
". Next match will begin at " + pattern.lastIndex;
print(msg);
}
print("After the search finishes, lastIndex = " + pattern.lastIndex);
Matched 'Java' at 0. Next match will begin at 4
Matched 'Java' at 9. Next match will begin at 13
After the search finishes, lastIndex = 0
Be careful not to use the exec() method in a loop when the search is not global,
because for the nonglobal match, it does not change the lastIndex property that will
make the loop an infinite loop. You should call the method only once for the nonglobal
match. The following code will run forever:
 
Search WWH ::




Custom Search