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:
# import library import re
""" We create a re.MatchObject and store it in match_object variable, '()' parenthesis are used to define a specific group """ match_object = re.match(r '(\d+)' ,
'128935' )
""" d in above pattern stands for numerical character + is used to match a consecutive set of characters satisfying a given condition so d+ will match a consecutive set of numerical characters """ # generating the tuple with the # starting and ending index 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.
# import library import re
""" We create a re.MatchObject and store it in match_object variable, '()' parenthesis are used to define a specific group""" match_object = re.match(r '(\d+)' ,
'geeks' )
""" d in above pattern stands for numerical character + is used to match a consecutive set of characters satisfying a given condition so d+ will match a
consecutive set of numerical characters """ # generating the tuple with the # starting and ending index 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'