例如:
我的字符串是:123456789 nn nn oo nn nn mlm nn203
。
我的目标是:nn
。
然后,我从头到尾匹配字符串,返回第一个匹配结果及其位置。
在这个例子中,结果是 nn
start in [-5] end in [-3]。
我写了简单的函数来完成这个过程,但是如何使用正则表达式来完成这个工作呢?
最佳答案
对于字符串本身,只需执行一次查找并使用最后一个:
import re
st='123456 nn1 nn2 nn3 nn4 mlm nn5 mlm'
print(re.findall(r'(nn\d+)',st)[-1])
打印nn5
您也可以使用 finditer
来做同样的事情,这样可以更轻松地找到相关索引:
print([(m.group(),m.start(),m.end()) for m in re.finditer(r'(nn\d+)',st)][-1])
打印 ('nn5', 27, 30)
如果你有很多匹配项,而你只想要最后一个,有时简单地反转字符串和模式是有意义的:
m=re.search(r'(\d+nn)',st[::-1])
offset=m.start(1)
print(st[-m.start(1)-len(m.group(1)):-m.start(1)])
或者,将您的模式修改为只有最后一个匹配可能满足的模式:
# since fixed width, you can use a lookbehind:
m=re.search(r'(...(?<=nn\d)(?!.*nn\d))',st)
if m: print(m.group(1))
或者,利用 .*
的贪婪性,它将始终返回多个匹配项中的最后一个:
# .* will skip to the last match of nn\d
m=re.search(r'.*(nn\d)', st)
if m: print(m.group(1))
任何这些打印 nn5
关于python - 如何使用正则表达式做反向搜索?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16510017/