re.MatchObject.span() Method in Python – regex
Last Updated :
02 Sep, 2020
re.MatchObject.span() method returns a tuple containing starting and ending index of the matched string. If group did not contribute to the match it returns(-1,-1).
Syntax: re.MatchObject.span()
Parameters: group (optional) By default this is 0.
Return: A tuple containing starting and ending index of the matched string. If group did not contribute to the match it returns(-1,-1).
AttributeError: If a matching pattern is not found then it raises AttributeError.
Consider the below example:
Example 1:
Python3
import re
match_object = re.match(r '(\d+)' ,
'128935' )
print (match_object.span())
|
Output:
(0, 6)
It’s time to understand the above program. We use a re.match() method to find a match in the given string(‘128935‘) the ‘d‘ indicates that we are searching for a numerical character and the ‘+‘ indicates that we are searching for continuous numerical characters in the given string. Note the use of ‘()‘ the parenthesis is used to define different subgroups.
Example 2: If a match object is not found then it raises AttributeError.
Python3
import re
match_object = re.match(r '(\d+)' ,
'geeks' )
print (match_object.span())
|
Output:
Traceback (most recent call last):
File "/home/18a058de83529572f8d50dc9f8bbd34b.py", line 17, in
print(match_object.span())
AttributeError: 'NoneType' object has no attribute 'span'
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...