Next / Previous / Contents / TCC Help System / NM Tech homepage

28.5.4. Methods on a MatchObject

A MatchObject is the object returned by .match() or other methods. Such an object has these methods and attributes:

.end([n])

Returns the location where a match ended. If no argument is given, returns the index of the first character past the match. If n is given, returns the index of the first character past where the nth group matched.

.endpos

The effective pe value passed to .match() or .search().

.group([n])

Retrieves the text that matched. If there are no arguments, or if n is zero, it returns the entire string that matched.

To retrieve just the text that matched the nth group, pass in an integer n, where the groups are numbered starting at 1. For example, for a MatchObject m, m.group(2) would return the text that matched the second group, or None if there were no second group.

If you have named the groups in your regular expression using a construct of the form (?P<name>...), the n argument can be the name as a string. For example, if you have a group (?P<year>[\d]{4}) (which matches four digits), you can retrieve that field using m.group('year').

.groups([default])

Return a tuple (s1,s2,...) containing all the matched strings, where si is the string that matched the ith group.

For groups that did not match, the corresponding value in the tuple will be None, or an optional default value that you specify in the call to this method.

.groupdict([default])

Return a dictionary whose keys are the named groups in the regular expression. Each corresponding value will be the text that matched the group. If a group did not match, the corresponding value will be None, or an alternate default value that you supply when you call the method.

.lastgroup

Holds the name of the last named group (using the (?P<n>r) construct) that matched. It will be None if no named groups matched, or if the last group that matched was a numbered group and not a named group.

.lastindex

Holds the index of the last group that matched, or None if no groups matched.

.pos

The effective ps value passed to .match() or .search().

.re

The regular expression object used to produce this MatchObject.

.span([n])

Returns a 2-tuple (m.start(n),m.end(n)).

.start([n])

Returns the location where a match started. If no argument is given, returns the index within the string where the entire match started. If an argument n is given, returns the index of the start of the match for the nth group.

.string

The s argument passed to .match() or .search().