Skip to content
Related Articles

Related Articles

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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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())

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

# 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())

chevron_right


Output:

Traceback (most recent call last):
  File "/home/18a058de83529572f8d50dc9f8bbd34b.py", line 17, in 
    print(match_object.span())
AttributeError: 'NoneType' object has no attribute 'span'

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :