Python正则表达式 – re.MatchObject.start() 和 re.MatchObject.end() 函数
在本文中,我们将看到re.MatchObject.start()和re.MatchObject.end()正则表达式方法。
re.MatchObject.start()
此方法返回组匹配的子字符串的第一个索引。
Syntax: re.MatchObject.start([group])
Parameter:
- group: (optional) group defaults to zero (meaning the whole matched substring). Return -1 if group exists but did not contribute to the match.
Return: Index of start of the substring matched by group.
AttributeError: If a matching pattern is not found then it raise AttributeError.
re.MatchObject.end()
此方法返回group 匹配的子字符串的最后一个索引。
Syntax: re.MatchObject.end([group])
Parameter:
- group: (optional) group defaults to zero (meaning the whole matched substring). Return -1 if group exists but did not contribute to the match.
Return: Index of end of the substring matched by group.
AttributeError: If a matching pattern is not found then it raise AttributeError.
考虑下面的例子:
示例 1:
Python3
import re
# getting the match of the the string
search_pattern = re.search('\d+',
'1234')
"""
d: stands for integer
+: means a consecutive set of
characters satisfying a condition.
Hence d+ will match consecutive
integer string
"""
print(search_pattern.string)
print(search_pattern.start())
print(search_pattern.end())
Python3
import re
# getting the match of the the string
search_pattern = re.search('\d+',
'abcd')
"""
d: stands for integer
+: means a consecutive set of characters
satisfying a condition.
Hence d+ will match consecutive
integer string
"""
print(search_pattern.start())
print(search_pattern.end())
输出:
1234
0
4
让我们理解代码。在代码的第三行中,我们使用re.search()方法在给定的字符串(' 1234 ') 中找到匹配的 ' d ' 表示我们正在搜索数字字符,“ + ”表示我们正在搜索给定字符串中的连续数字字符。我们得到的结果是一个re.MatchObject ,它存储在 search_pattern 中。如果你打印search_pattern.字符串你会得到'1234'作为输出。
在上面的示例中, search_pattern.start()返回值0 ,因为给定字符串中匹配字符串的第一个元素的索引为 0,而search_pattern.end()返回4 ,即结束索引之后的结束索引字符串。
示例 2:
Python3
import re
# getting the match of the the string
search_pattern = re.search('\d+',
'abcd')
"""
d: stands for integer
+: means a consecutive set of characters
satisfying a condition.
Hence d+ will match consecutive
integer string
"""
print(search_pattern.start())
print(search_pattern.end())
输出:
Traceback (most recent call last):
File "/home/4f904f4b53a786e10faa03122533f96b.py", line 13, in
print(search_pattern.start())
AttributeError: 'NoneType' object has no attribute 'start'