As in Recipe 3.7, you have a regular expression that matches a substring of the subject text, but this time you want to match just one part of that substring. To isolate the part you want, you added a capturing group to your regular expression, as described in Recipe 2.9.
For example, the regular expression ‹http://([a-z0-9.-]+)
› matches http://www.regexcookbook.com
in the string
Please visit
http://www.regexcookbook.com for more information
. The part
of the regex inside the first capturing group matches www.regexcookbook.com
, and
you want to retrieve the domain name captured by the first capturing
group into a string variable.
We’re using this simple regex to illustrate the concept of capturing groups. See Chapter 8 for more accurate regular expressions for matching URLs.
For quick one-off matches, you can use the static call:
string resultString = Regex.Match(subjectString, "http://([a-z0-9.-]+)").Groups[1].Value;
To use the same regex repeatedly, construct a Regex
object:
Regex regexObj = new Regex("http://([a-z0-9.-]+)"); string resultString = regexObj.Match(subjectString).Groups[1].Value;
For quick one-off matches, you can use the static call:
Dim ResultString = Regex.Match(SubjectString, "http://([a-z0-9.-]+)").Groups(1).Value
To use the same regex repeatedly, construct a Regex
object:
Dim RegexObj As New Regex("http://([a-z0-9.-]+)") Dim ResultString = RegexObj.Match(SubjectString).Groups(1).Value
String resultString = null; Pattern regex = Pattern.compile("http://([a-z0-9.-]+)"); Matcher regexMatcher = regex.matcher(subjectString); if (regexMatcher.find()) { resultString = regexMatcher.group(1); }
var result; var match = /http://([a-z0-9.-]+)/.exec(subject); if (match) { result = match[1]; } else { result = ""; }
if (preg_match('%http://([a-z0-9.-]+)%', $subject, $groups)) { $result = $groups[1]; } else { $result = ''; }
For quick one-off matches, you can use the global function:
matchobj = re.search("http://([a-z0-9.-]+)", subject) if matchobj: result = matchobj.group(1) else: result = ""
To use the same regex repeatedly, use a compiled object:
reobj = re.compile("http://([a-z0-9.-]+)") matchobj = reobj.search(subject) if match: result = matchobj.group(1) else: result = ""
You can use the =~
operator and its magic numbered variables,
such as $1
:
if subject =~ %r!http://([a-z0-9.-]+)! result = $1 else result = "" end
Alternatively, you can call the match
method on a Regexp
object:
matchobj = %r!http://([a-z0-9.-]+)!.match(subject) if matchobj result = matchobj[1] else result = "" end
Recipe 2.10 and Recipe 2.21 explain how you can use numbered backreferences in the regular expression and the replacement text to match the same text again, or to insert part of the regex match into the replacement text. You can use the same reference numbers to retrieve the text matched by one or more capturing groups in your code.
In regular expressions, capturing groups are numbered starting at one. Programming languages typically start numbering arrays and lists at zero. All programming languages discussed in this book that store capturing groups in an array or list use the same numbering for capturing groups as the regular expression, starting at one. The zeroth element in the array or list is used to store the overall regular expression match. This means that if your regular expression has three capturing groups, the array storing their matches will have four elements. Element zero holds the overall match, and elements one, two, and three store the text matched by the three capturing groups.
To retrieve details about capturing groups, we again
resort to the Regex.Match()
member function, first explained
in Recipe 3.7. The returned Match
object has a property
called Groups
. This is
a collection property of type GroupCollection
. The collection holds the
details for all the capturing groups in your regular expression.
Groups[1]
holds the
details for the first capturing group, Groups[2]
the second group, and so on.
The Groups
collection holds one Group
object for each capturing group. The
Group
class has the
same properties as the Match
class, except for the Groups
property. Match.Groups[1].Value
returns the text matched
by the first capturing group, in the same way that Match.Value
returns the overall regex match.
Match.Groups[1].Index
and Match.Groups[1].Length
return the starting
position and length of the text matched by the group. See Recipe 3.8 for more details on Index
and
Length
.
Groups[0]
holds
the details for the overall regex match, which are also held by the
match object directly. Match.Value
and Match.Groups[0].Value
are equivalent.
The Groups
collection does not throw an exception if you pass an invalid group
number. For example, Groups[-1]
still returns a Group
object, but the properties
of that Group
object
will indicate that the fictional capturing group -1
failed to match. The best way
to test this is to use the Success
property. Groups[-1].Success
will return false
.
To determine how many capturing groups there are, check
Match.Groups.Count
. The Count
property follows the same convention as the Count
property for all collection objects in .NET: it returns the number of
elements in the collection, which is the highest allowed index plus
one. In our example, the Groups
collection holds Groups[0]
and Groups[1]
. Groups.Count
thus returns
2
.
The code for getting either the text matched by a
capturing group or the match details of a capturing group is
practically the same as that for the whole regex match, as shown in
the preceding two recipes. The group()
,
start()
and end()
,
methods of the Matcher
class all take one optional parameter. Without this parameter, or with
this parameter set to zero, you get the match or positions of the
whole regex match.
If you pass a positive number, you get the details of that
capturing group. Groups are numbered starting at one, just like
backreferences in the regular expression itself. If you specify a
number higher than the number of capturing groups in your regular
expression, these three functions throw an IndexOutOfBoundsException
. If the capturing
group exists but did not participate in the match, group(
returns
n
)null
, whereas start(
and n
)end(
both return
n
)-1
.
As explained in the previous recipe, the exec()
method of a regular expression object returns an array with details
about the match. Element zero in the array holds the overall regex
match. Element one holds the text matched by the first capturing
group, element two stores the second group’s match, etc.
If the regular expression cannot match the string at all,
regexp.exec()
returns null
.
Recipe 3.7 explains how you
can get the text matched by the regular expression by passing a third
parameter to preg_match()
. When preg_match()
returns 1
, the parameter is filled with an array.
Element zero holds a string with the overall regex match.
Element one holds the text matched by the first capturing group, element two the text from the second group, and so on. The length of the array is the number of capturing groups plus one. Array indexes correspond to backreference numbers in the regular expression.
If you specify the PREG_OFFSET_CAPTURE
constant as the fourth
parameter, as explained in the previous recipe, then the length of the
array is still the number of capturing groups plus one. But instead of
holding a string at each index, the array will hold subarrays with two
elements. Subelement zero is the string with the text matched by the
overall regex or the capturing group. Subelement one is an integer
that indicates the position in the subject string at which the matched
text starts.
When the pattern-matching operator m//
finds
a match, it sets several special variables. Those include the numbered
variables $1
, $2
, $3
, etc., which hold the part of the string
matched by the capturing groups in the regular expression.
The solution to this problem is almost identical to the
one in Recipe 3.7. Instead of calling
group()
without any parameters, we specify the number of the capturing group
we’re interested in. Call group(1)
to get the text matched by the first
capturing group, group(2)
for the second group, and so on. Python
supports up to 99 capturing groups.
Group number 0 is the overall regular expression match. If
you pass a number greater than the number of capturing groups in your
regular expression, then group()
raises an IndexError
exception. If the group number is valid but the group did not
participate in the regex match, group()
returns None
.
You can pass multiple group numbers to group()
to get the text matched by several capturing groups in one call. The
result will be a list of strings.
If you want to retrieve a tuple with the text matched by all the
capturing groups, you can call the groups()
method of MatchObject
.
The tuple will hold None
for groups that did not participate in the
match. If you pass a parameter to groups()
,
that value is used instead of None
for groups that did not participate in the
match.
If you want a dictionary instead of a tuple with the text
matched by the capturing groups, call groupdict()
instead of groups()
.
You can pass a parameter to groupdict()
to put something other than
None
in the dictionary
for groups that did not participate in the match.
Recipe 3.8 explains the
$~
variable and the MatchData
object. In an array context, this object evaluates to an array with
the text matched by all the capturing groups in your regular
expression. Capturing groups are numbered starting at 1
, just like backreferences in
the regular expression. Element 0
in the array holds the overall regular
expression match.
$1
, $2
, and beyond are special
read-only variables. $1
is a shortcut to $~[1]
,
which holds the text matched by the first capturing group. $2
retrieves the second group,
and so on.
If your regular expression uses named capturing groups, you can use the group’s name to retrieve its match in your code.
For quick one-off matches, you can use the static call:
string resultString = Regex.Match(subjectString, "http://(?<domain>[a-z0-9.-]+)").Groups["domain"].Value;
To use the same regex repeatedly, construct a Regex
object:
Regex regexObj = new Regex("http://(?<domain>[a-z0-9.-]+)"); string resultString = regexObj.Match(subjectString).Groups["domain"].Value;
In C#, there’s no real difference in the code for getting the
Group
object for a named group compared with a numbered group. Instead of
indexing the Groups
collection with an integer, index it with a string. Also in this case,
.NET will not throw an exception if the group does not exist. Match.Groups["nosuchgroup"].Success
merely
returns false
.
For quick one-off matches, you can use the static call:
Dim ResultString = Regex.Match(SubjectString, "http://(?<domain>[a-z0-9.-]+)").Groups("domain").Value
To use the same regex repeatedly, construct a Regex
object:
Dim RegexObj As New Regex("http://(?<domain>[a-z0-9.-]+)") Dim ResultString = RegexObj.Match(SubjectString).Groups("domain").Value
In VB.NET, there’s no real difference in the code for getting
the Group
object for a named group compared with a numbered group. Instead of
indexing the Groups
collection with an integer, index it with a string. Also in this case,
.NET will not throw an exception if the group does not exist. Match.Groups("nosuchgroup").Success
merely
returns False
.
String resultString = null; Pattern regex = Pattern.compile("http://(?<domain>[a-z0-9.-]+)"); Matcher regexMatcher = regex.matcher(subjectString); if (regexMatcher.find()) { resultString = regexMatcher.group("domain"); }
Java 7 adds support for named capturing groups. It also
adds an overload to the Matcher.group()
method that takes the name of a
capturing group as its parameter, and returns the text matched by that
capturing group. It throws an IllegalArgumentException
if you pass the name of
a group that does not exist.
Unfortunately, the Matcher.start()
and Matcher.end()
methods do not have similar
overloads. If you want to get the start or the end of a named
capturing group, you have to reference it by its number. Java numbers
both named and unnamed capturing groups from left to right. The
group(), start(), and end() methods of the Matcher
class all take one optional parameter. Without this parameter, or with
this parameter set to zero, you get the match or positions of the
whole regex match.
var result; var match = XRegExp.exec(subject, XRegExp("http://(?<domain>[a-z0-9.-]+)")); if (match) { result = match.domain; } else { result = ""; }
XRegExp extends JavaScript’s
regular expression syntax with named capture. XReg
Exp.exec()
adds a property for each named
capturing group to the match
object it returns, allowing you
to easily reference each group by name.
if (preg_match('%http://(?P<domain>[a-z0-9.-]+)%', $subject, $groups)) { $result = $groups['domain']; } else { $result = ''; }
If your regular expression has named capturing groups,
then the array assigned to $groups
is an associative array. The text
matched by each named capturing group is added to the array twice. You
can retrieve the matched text by indexing the array with either the
group’s number or the group’s name. In the code sample, $groups[0]
stores the overall
regex match, whereas both $groups[1]
and $groups['domain']
store the text matched by the
regular expression’s only capturing group.
if ($subject =~ '!http://(?<domain>[a-z0-9.-]+)%!) { $result = $+{'domain'}; } else { $result = ''; }
Perl supports named capturing groups starting with
version 5.10. The %+
hash
stores the text matched by all named capturing groups. Perl numbers
named groups along with numbered groups. In this example, both
$1
and $+{name}
store the text matched
by the regular expression’s only capturing group.
matchobj = re.search("http://(?P<domain>[a-z0-9.-]+)", subject) if matchobj: result = matchobj.group("domain") else: result = ""
If your regular expression has named capturing groups,
you can pass the group’s name instead of its number to the group()
method.
Ruby 1.9 adds support for named capture to the regular
expression syntax. It also extends the $~
variable and the MatchData
object explained in Recipe 3.8 to
support named capture. $~["name"]
or matchobj["name"]
returns the text matched by the
named group “name.” Call matchobj.begin("name")
and matchobj.end("name")
to retrieve
the beginning and ending positions of the match of a named
group.