详解Python re.search.lastindex函数:返回最后匹配的组的索引

  • Post category:Python

Python中的re模块是用于对字符串进行正则表达式匹配的模块。re.search()函数用于在字符串中查找正则表达式模式匹配的第一个位置,并返回一个匹配对象。如果匹配失败,则返回None。

re.search.lastindex函数是re模块中的一个方法,用于返回匹配最后一次匹配的正则表达式子组的索引。索引从1开始,如果没有子组匹配成功,则返回None。

使用方法如下:

import re

pattern = '^(\d{3})-(\d{3,8})$'
string = '010-12345'
match = re.search(pattern, string)

print(match)  # <re.Match object; span=(0, 9), match='010-12345'>
print(match.lastindex)  # 2

以上实例中,正则表达式^(\d{3})-(\d{3,8})$可以匹配一个形如010-12345的字符串,其中^(\d{3})匹配以三个数字开头的字符串,-(\d{3,8})$匹配以一个-连字符后跟3-8个数字结尾的字符串。

在这个实例中,re.search()方法返回一个匹配对象match,而match.lastindex方法返回2,表示最后一次匹配中第2个正则表达式组(即(\d{3,8}))匹配成功。

下面是另一个使用re.search.lastindex()函数的实例:

import re

pattern = '\d+(\.\d+)?'
string = 'the price is 50.2 dollar'
match = re.search(pattern, string)

print(match)  # <re.Match object; span=(16, 21), match='50.2'>
print(match.lastindex)  # 1

在这个实例中,正则表达式\d+(\.\d+)?可以匹配一个含有小数的数字。但是小数点后的数字是可选的,所以使用了(\.\d+)?来表示一个点和至少一个数字,它可以匹配0次或1次。

在这个实例中,re.search()方法匹配到了数字50.2,即(\.\d+)?匹配到了。match.lastindex方法返回1,表示最后一次匹配中只有一个正则表达式组匹配成功。

综上所述,re.search.lastindex函数的作用是返回最后一次匹配的正则表达式子组的索引,使用方法是在匹配成功后通过Match对象调用该方法。