3.10. Retrieve a List of All Matches

Problem

All the preceding recipes in this chapter deal only with the first match that a regular expression can find in the subject string. But in many cases, a regular expression that partially matches a string can find another match in the remainder of the string. And there may be a third match after the second, and so on. For example, the regex d+ can find six matches in the subject string The lucky numbers are 7, 13, 16, 42, 65, and 99: 7, 13, 16, 42, 65, and 99.

You want to retrieve the list of all substrings that the regular expression finds when it is applied repeatedly to the remainder of the string, after each match.

Solution

C#

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

MatchCollection matchlist = Regex.Matches(subjectString, @"d+");

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

Regex regexObj = new Regex(@"d+");
MatchCollection matchlist = regexObj.Matches(subjectString);

VB.NET

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

Dim MatchList = Regex.Matches(SubjectString, "d+")

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 MatchList = RegexObj.Matches(SubjectString)

Java

List<String> resultList = new ArrayList<String>();
Pattern regex = Pattern.compile("\d+");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    resultList.add(regexMatcher.group());
}

JavaScript

var list = subject.match(/d+/g);

PHP

preg_match_all('/d+/', $subject, $result, PREG_PATTERN_ORDER);
$result = $result[0];

Perl

@result = $subject =~ m/d+/g;

This only works for regular expressions that don’t have capturing groups, so use noncapturing groups instead. See Recipe 2.9 for details.

Python

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

result = re.findall(r"d+", subject)

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

reobj = re.compile(r"d+")
result = reobj.findall(subject)

Ruby

result = subject.scan(/d+/)

Discussion

.NET

The Matches() method of the Regex class applies the regular expression repeatedly to the string, until all matches have been found. It returns a MatchCollection object that holds all the matches. The subject string is always the first parameter. This is the string in which the regular expression will try to find a match. The first parameter must not be null. Otherwise, Matches() will throw an ArgumentNullException.

If you want to get the regex matches in only a small number of strings, you can use the static overload of Matches(). Pass your subject string as the first parameter and your regular expression as the second parameter. You can pass regular expression options as an optional third parameter.

If you’ll be processing many strings, construct a Regex object first, and use that to call Matches(). The subject string is then the only required parameter. You can specify an optional second parameter to indicate the character index at which the regular expression should begin the check. Essentially, the number you pass as the second parameter is the number of characters at the start of your subject string that the regular expression should ignore. This can be useful when you’ve already processed the string up to a point and want to check whether the remainder should be processed further. If you specify the number, it must be between zero and the length of the subject string. Otherwise, IsMatch() throws an ArgumentOutOfRangeException.

The static overloads do not allow for the parameter that specifies where the regex attempt should start in the string. There is no overload that allows you to tell Matches() to stop before the end of the string. If you want to do that, you could call Regex.Match("subject", start, stop) in a loop, as shown in the next recipe, and add all the matches it finds to a list of your own.

Java

Java does not provide a function that retrieves the list of matches for you. You can easily do this in your own code by adapting Recipe 3.7. Instead of calling find() in an if statement, do it in a while loop.

To use the List and ArrayList classes, as in the example, put import java.util.*; at the start of your code.

JavaScript

This code calls string.match(), just like the JavaScript solution to Recipe 3.7. There is one small but very important difference: the /g flag. Regex flags are explained in Recipe 3.4.

The /g flag tells the match() function to iterate over all matches in the string and put them into an array. In the code sample, list[0] will hold the first regex match, list[1] the second, and so on. Check list.length to determine the number of matches. If no matches can be found at all, string.match returns null as usual.

The elements in the array are strings. When you use a regex with the /g flag, string.match() does not provide any further details about the regular expression match. If you want to get match details for all regex matches, iterate over the matches as explained in Recipe 3.11.

PHP

All the previous PHP recipes used preg_match(), which finds the first regex match in a string. preg_match_all() is very similar. The key difference is that it will find all matches in the string. It returns an integer indicating the number of times the regex could match.

The first three parameters for preg_match_all() are the same as the first three for preg_match(): a string with your regular expression, the string you want to search through, and a variable that will receive an array with the results. The only differences are that the third parameter is required and the array is always multidimensional.

For the fourth parameter, specify either the constant PREG_PATTERN_ORDER or PREG_SET_ORDER. If you omit the fourth parameter, PREG_PATTERN_ORDER is the default.

If you use PREG_PATTERN_ORDER, you will get an array that stores the details of the overall match at element zero, and the details of capturing groups one and beyond at elements one and beyond. The length of the array is the number of capturing groups plus one. This is the same order used by preg_match(). The difference is that instead of each element holding a string with the only regex match found by preg_match(), each element holds a subarray with all the matches found by preg_matches(). The length of each subarray is the same as the value returned by preg_matches().

To get a list of all the regex matches in the string, discarding text matched by capturing groups, specify PREG_PATTERN_ORDER and retrieve element zero in the array. If you’re only interested in the text matched by a particular capturing group, use PREG_PATTERN_ORDER and the capturing group’s number. For example, specifying $result[1] after calling preg_match('%http://([a-z0-9.-]+)%', $subject, $result) gives you the list of domain names of all the URLs in your subject string.

PREG_SET_ORDER fills the array with the same strings, but in a different way. The length of the array is the value returned by preg_matches(). Each element in the array is a subarray, with the overall regex match in subelement zero and the capturing groups in elements one and beyond. If you specify PREG_SET_ORDER, then $result[0] holds the same array as if you had called preg_match().

You can combine PREG_OFFSET_CAPTURE with PREG_PATTERN_ORDER or PREG_SET_ORDER. Doing so has the same effect as passing PREG_OFFSET_CAPTURE as the fourth parameter to preg_match(). Instead of each element in the array holding a string, it will hold a two-element array with the string and the offset at which that string occurs in the original subject string.

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 list context, it will find all the matches and return them. In this recipe, the list variable to the left of the assignment operator provides the list context.

If the regular expression does not have any capturing groups, the list will contain the overall regex matches. If the regular expression does have capturing groups, the list will contain the text matched by all the capturing groups for each regex match. The overall regex match is not included, unless you put a capturing group around the whole regex. If you only want to get a list of overall regex matches, replace all capturing groups with noncapturing groups. Recipe 2.9 explains both kinds of grouping.

Python

The findall() function in the re module searches repeatedly through a string to find all 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.findall() function calls re.compile(), and then calls the findall() method on the compiled regular expression object. This method has only one required parameter: the subject string.

The findall() method takes two optional parameters that the global re.findall() function does not support. After the subject string, you can pass the character position in the string at which findall() should begin its search. If you omit this parameter, findall() processes 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.

No matter how you call findall(), the result is always a list with all the matches that could be found. If the regex has no capturing groups, you get a list of strings. If it does have capturing groups, you get a list of tuples with the text matched by all the capturing groups for each regex match.

Ruby

The scan() method of the String class takes a regular expression as its only parameter. It iterates over all the regular expression matches in the string. When called without a block, scan() returns an array of all regex matches.

If your regular expression does not contain any capturing groups, scan() returns an array of strings. The array has one element for each regex match, holding the text that was matched.

When there are capturing groups, scan() returns an array of arrays. The array has one element for each regex match. Each element is an array with the text matched by each of the capturing groups. Subelement zero holds the text matched by the first capturing group, subelement one holds the second capturing group, etc. The overall regex match is not included in the array. If you want the overall match to be included, enclose your entire regular expression with an extra capturing group:

Ruby does not provide an option to make scan() return an array of strings when the regex has capturing groups. Your only solution is to replace all named and numbered capturing groups with noncapturing groups.

See Also

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

Recipe 3.11 shows code to iterate over all the matches a regex can find in a string.

Recipe 3.12 shows code to iterate over all the matches a regex can find in a string and only retain those matches that meet certain criteria.

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

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