3.11. Iterate over All Matches

Problem

The previous recipe shows how a regex could be applied repeatedly to a string to get a list of matches. Now you want to iterate over all the matches in your own code.

Solution

C#

You can use the static call when you process only a small number of strings with the same regular expression:

Match matchResult = Regex.Match(subjectString, @"d+");
while (matchResult.Success) {
    // Here you can process the match stored in matchResult
    matchResult = matchResult.NextMatch();
}

Construct a Regex object if you want to use the same regular expression with a large number of strings:

Regex regexObj = new Regex(@"d+");
matchResult = regexObj.Match(subjectString);
while (matchResult.Success) {
    // Here you can process the match stored in matchResult
    matchResult = matchResult.NextMatch();
}

VB.NET

You can use the static call when you process only a small number of strings with the same regular expression:

Dim MatchResult = Regex.Match(SubjectString, "d+")
While MatchResult.Success
    'Here you can process the match stored in MatchResult
    MatchResult = MatchResult.NextMatch
End While

Construct a Regex object if you want to use the same regular expression with a large number of strings:

Dim RegexObj As New Regex("d+")
Dim MatchResult = RegexObj.Match(SubjectString)
While MatchResult.Success
    'Here you can process the match stored in MatchResult
    MatchResult = MatchResult.NextMatch
End While

Java

Pattern regex = Pattern.compile("\d+");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    // Here you can process the match stored in regexMatcher
}

JavaScript

If your regular expression may yield a zero-length match, or if you’re simply not sure about that, make sure to work around cross-browser issues dealing with zero-length matches and exec():

var regex = /d+/g;
var match = null;
while (match = regex.exec(subject)) {
  // Don't let browsers get stuck in an infinite loop
  if (match.index == regex.lastIndex) regex.lastIndex++;
  // Here you can process the match stored in the match variable
}

If you know for sure your regex can never find a zero-length match, you can iterate over the regex directly:

var regex = /d+/g;
var match = null;
while (match = regex.exec(subject)) {
  // Here you can process the match stored in the match variable
}

XRegExp

If you’re using the XRegExp JavaScript library, you can use the dedicated XRegExp.forEach() method to iterate over matches:

XRegExp.forEach(subject, /d+/, function(match) {
  // Here you can process the match stored in the match variable
});

PHP

preg_match_all('/d+/', $subject, $result, PREG_PATTERN_ORDER);
for ($i = 0; $i < count($result[0]); $i++) {
    # Matched text = $result[0][$i];
}

Perl

while ($subject =~ m/d+/g) {
    # matched text = $&
}

Python

If you process only a small number of strings with the same regular expression, you can use the global function:

for matchobj in re.finditer(r"d+", subject):
    # Here you can process the match stored in the matchobj variable

To use the same regex repeatedly, use a compiled object:

reobj = re.compile(r"d+")
for matchobj in reobj.finditer(subject):
    # Here you can process the match stored in the matchobj variable

Ruby

subject.scan(/d+/) {|match|
    # Here you can process the match stored in the match variable
}

Discussion

.NET

Recipe 3.7 explains how to use the Match() member function of the Regex class to retrieve the first regular expression match in the string. To iterate over all matches in the string, we again call the Match() function to retrieve the details of the first match. The Match() function returns an instance of the Match class, which we store in the variable matchResult. If the Success property of the matchResult object holds true, we can begin our loop.

At the start of the loop, you can use the properties of the Match class to process the details of the first match. Recipe 3.7 explains the Value property, Recipe 3.8 explains the Index and Length properties, and Recipe 3.9 explains the Groups collection.

When you’re done with the first match, call the NextMatch() member function on the matchResult variable. Match.NextMatch() returns an instance of the Match class, just like Regex.Match() does. The newly returned instance holds the details of the second match.

Assigning the result from matchResult.NextMatch() to the same matchResult variable makes it easy to iterate over all matches. We have to check matchResult.Success again to see whether NextMatch() did in fact find another match. When NextMatch() fails, it still returns a Match object, but its Success property will be set to false. By using a single matchResult variable, we can combine the initial test for success and the test after the call to NextMatch() into a single while statement.

Calling NextMatch() does not invalidate the Match object you called it on. If you want, you could keep the full Match object for each regular expression match.

The NextMatch() method does not accept any parameters. It uses the same regular expression and subject string as you passed to the Regex.Match() method. The Match object keeps references to your regular expression and subject string.

You can use the static Regex.Match() call, even when your subject string contains a very large number of regex matches. Regex.Match() will compile your regular expression once, and the returned Match object will hold a reference to the compiled regular expression. Match.MatchAgain() uses the previously compiled regular expression referenced by the Match object, even when you used the static Regex.Match() call. You need to instantiate the Regex class only if you want to call Regex.Match() repeatedly (i.e., use the same regex on many strings).

Java

Iterating over all the matches in a string is very easy in Java. Simply call the find() method introduced in Recipe 3.7 in a while loop. Each call to find() updates the Matcher object with the details about the match and the starting position for the next match attempt.

JavaScript

Before you begin, make sure to specify the /g flag if you want to use your regex in a loop. This flag is explained in Recipe 3.4. while (regexp.exec()) finds all numbers in the subject string when regexp = /d+/g. If regexp = /d+/, then while (regexp.exec()) finds the first number in the string again and again, until your script crashes or is forcibly terminated by the browser.

Note that while (/d+/g.exec()) (looping over a literal regex with /g) also will get stuck in the same infinite loop, at least with certain JavaScript implementations, because the regular expression is recompiled during each iteration of the while loop. When the regex is recompiled, the starting position for the match attempt is reset to the start of the string. Assign the regular expression to a variable outside the loop, to make sure it is compiled only once.

Recipes 3.8 and 3.9 explain the object returned by regexp.exec(). This object is the same, regardless of whether you use exec() in a loop. You can do whatever you want with this object.

The only effect of the /g is that it updates the lastIndex property of the regexp object on which you’re calling exec(). This works even when you’re using a literal regular expression, as shown in the second JavaScript solution for this recipe. Next time you call exec(), the match attempt will begin at lastIndex. If you assign a new value to lastIndex, the match attempt will begin at the position you specified.

There is, unfortunately, one major problem with lastIndex. If you read the ECMA-262v3 standard for JavaScript literally, then exec() should set lastIndex to the first character after the match. This means that if the match is zero characters long, the next match attempt will begin at the position of the match just found, resulting in an infinite loop.

All modern browsers implement the standard as written, which means regexp.exec() may get stuck in an infinite loop. This outcome is not unlikely. For example, you can use re = /^.*$/gm; while (re.exec()) to iterate over all lines in a multiline string. If the string has a blank line, your script will get stuck on it.

The workaround is to increment lastIndex in your own code if the exec() function hasn’t already done this. The first JavaScript solution to this recipe shows you how. If you’re unsure, simply paste in this one line of code and be done with it.

Older versions of Internet Explorer avoided this problem by incrementing lastIndex by one if the match is zero-length. Internet Explorer 9 only does this when running in quirks mode. This is why Recipe 3.7 claims that you cannot use lastIndex to determine the end of the match, as you’ll get incorrect values in Internet Explorer’s quirks mode.

All other regular expression engines discussed in this book deal with this by automatically starting the next match attempt one character further in the string, if the previous match was zero-length.

This problem does not exist with string.replace() (Recipe 3.14) or when finding all matches with string.match() (Recipe 3.10). For these methods, which use lastIndex internally, the ECMA-262v3 standard does state that lastIndex must be incremented for each zero-length match.

XRegExp

If you’re using the XRegExp JavaScript library, the dedicated XRegExp.forEach() method makes your life much easier. Pass your subject string, your regular expression, and a callback function to this method. Your callback function will be called for each match of the regular expression in the subject string. The callback will receive the match array, the index of the match (counting from zero), the subject string, and the regex being used to search the string as parameters. If you pass a fourth parameter to XRegExp.forEach(), then this will be used as the context that is used as the value for this in the callback and will also be returned by XRegExp.forEach() after it finishes finding matches.

XRegExp.forEach() ignores the global and lastIndex properties of the RegExp object you pass to it. It always iterates over all matches. Use XRegExp.forEach() to neatly sidestep any issues with zero-length matches.

XRegExp also provides its own XRegExp.exec() method. This method ignores the lastIndex property. Instead, it takes an optional third parameter that lets you specify the position at which the match attempt should begin. To find the next match, specify the position where the previous match ended. If the previous match was zero-length, specify the position where the match ended plus one.

PHP

The preg_match() function takes an optional fifth parameter to indicate the position in the string at which the match attempt should start. You could adapt Recipe 3.8 to pass $matchstart + $matchlength as the fifth parameter upon the second call to preg_match() to find the second match in the string, and repeat that for the third and following matches until preg_match() returns 0. Recipe 3.18 uses this method.

In addition to requiring extra code to calculate the starting offset for each match attempt, repeatedly calling preg_match() is inefficient, because there’s no way to store a compiled regular expression in a variable. preg_match() has to look up the compiled regular expression in its cache each time you call it.

An easier and more efficient solution is to call preg_match_all(), as explained in the previous recipe, and iterate over the array with the match results.

Perl

Recipe 3.4 explains that you need to add the /g modifier to enable your regex to find more than one match in the subject string. If you use a global regex in a scalar context, it will try to find the next match, continuing at the end of the previous match. In this recipe, the while statement provides the scalar context. All the special variables, such as $& (explained in Recipe 3.7), are available inside the while loop.

Python

The finditer() function in re returns an iterator that you can use to find all the matches of the regular expression. Pass your regular expression as the first parameter and the subject string as the second parameter. You can pass the regular expression options in the optional third parameter.

The re.finditer() function calls re.compile(), and then calls the finditer() method on the compiled regular expression object. This method has only one required parameter: the subject string.

The finditer() method takes two optional parameters that the global re.finditer() function does not support. After the subject string, you can pass the character position in the string at which finditer() should begin its search. If you omit this parameter, the iterator will process the whole subject string. If you specify a starting position, you can also specify an ending position. If you don’t specify an ending position, the search runs until the end of the string.

Ruby

The scan() method of the String class takes a regular expression as its only parameter and iterates over all the regular expression matches in the string. When it is called with a block, you can process each match as it is found.

If your regular expression does not contain any capturing groups, specify one iterator variable in the block. This variable will receive a string with the text matched by the regular expression.

If your regex does contain one or more capturing groups, list one variable for each group. The first variable will receive a string with the text matched by the first capturing group, the second variable receives the second capturing group, and so on. No variable will be filled with the overall regex match. If you want the overall match to be included, enclose your entire regular expression with an extra capturing group.

subject.scan(/(a)(b)(c)/) {|a, b, c|
    # a, b, and c hold the text matched by the three capturing groups
}

If you list fewer variables than there are capturing groups in your regex, you will be able to access only those capturing groups for which you provided variables. If you list more variables than there are capturing groups, the extra variables will be set to nil.

If you list only one iterator variable and your regex has one or more capturing groups, the variable will be filled with an array of strings. The array will have one string for each capturing group. If there is only one capturing group, the array will have a single element:

subject.scan(/(a)(b)(c)/) {|abc|
    # abc[0], abc[1], and abc[2] hold the text
    # matched by the three capturing groups
}

See Also

Recipe 3.12 expands on this recipe by only retaining those matches that meet certain criteria.

Recipe 3.7 shows code to get only the first regex match.

Recipe 3.8 shows code to determine the position and length of the match.

Recipe 3.10 shows code to get a list of all the matches a regex can find in a string.

Construct a Parser shows how you can build a simple parser by iterating over all the matches of a regular expression.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset