Match-object
Match-object is an object with information about matches of regular expression in a string. Match object can be obtained by applying the following methods: fullmatch
, match
, search
.
You can extract information from a match object using the basic methods.
Basic methods applied to the match object
Method | Purpose |
---|---|
group |
Returns the zero pocket. |
groups |
Returns a tuple from pockets. |
groupdict |
Returns a dictionary of named pockets. |
span |
Returns the first and last indices of a tuple from a single pocket. |
start |
Returns the first index of a tuple from a single pocket. |
end |
Returns the last index of a tuple from a single pocket. |
Example . Match-object without method
Let's apply the match
method to our string:
txt = '123 456 789'
res = re.match('\d+', txt)
print(res)
Result of code execution:
<re.Match object; span=(0, 3), match='123'>
Example . group method
Now let's derive the zero pocket from the Match object using the group
method:
txt = '123 456 789'
res = re.match('\d+', txt)
print(res.group())
Result of code execution:
'123'
Example . The groups method
Let's apply the groups
method to the resulting object to output tuples of pockets:
txt = '123 456 789'
res = re.match('(\d)(\d)', txt)
print(res.groups())
Result of code execution:
('1', '2')
Example . groupdict method
To output a dictionary of named pockets, you can use the groupdict
method:
res = re.match('(?P<test1>\d)(?P<test2>\d)', txt)
print(res.groupdict())
Result of code execution:
{'test1': '1', 'test2': '2'}
Example . Span Method
Let's print a tuple from the first and last indices of a single tuple. To do this, we use the span
method:
res = re.match('\d+', txt)
print(res.span())
After running the code, you will see a tuple consisting of two indices. But notice that the last value is one greater than the final index:
(0, 3)
Example . Methods start and end
To return each index separately, you can use the start
and end
methods:
res = re.match('\d+', txt)
print(res.start())
print(res.end())
Result of code execution:
0
3