📌  相关文章
📜  Python中的 re.MatchObject.span() 方法——正则表达式

📅  最后修改于: 2022-05-13 01:55:11.185000             🧑  作者: Mango

Python中的 re.MatchObject.span() 方法——正则表达式

re.MatchObject.span() 方法返回一个元组,其中包含匹配字符串的开始和结束索引。如果组对匹配没有贡献,则返回(-1,-1)。

考虑下面的例子:

示例 1:

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


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


输出:

(0, 6)    

是时候理解上面的程序了。我们使用re.match()方法在给定字符串(' 128935 ') 中查找匹配项,' d ' 表示我们正在搜索数字字符,' + ' 表示我们正在搜索连续的数字字符给定的字符串。注意使用' () '的括号是用来定义不同的子组。

示例 2:如果未找到匹配对象,则会引发 AttributeError。

Python3

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

输出:

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