如何使用正则表达式做反向搜索? [英] How to use regular expressions do reverse search?
问题描述
例如:
我的字符串是:123456789 nn nn oo nn nn mlm nn203
.
我的目标是:nn
.
然后,我从头到尾匹配字符串,并返回第一个匹配结果及其位置.
在这个例子中,结果是 nn
start in [-5] end in [-3].
我写了一个简单的函数来做这个过程,但是如何使用正则表达式来做这个工作?
Then, I match string from the end to the beginning and return the first match result and its postion.
In this examlpe, the result is nn
start in [-5] end in [-3].
I wrote the simple funcitonto do this process, but how to use regular expressions to do this job?
推荐答案
对于字符串本身,只需执行 findall 并使用最后一个:
For the string itself, just do a findall and use the last one:
import re
st='123456 nn1 nn2 nn3 nn4 mlm nn5 mlm'
print re.findall(r'(nn\d+)',st)[-1]
打印nn5
您也可以使用 finditer
来做同样的事情,这样可以更轻松地找到相关索引:
You can also do the same thing using finditer
which makes it easier finding the relevant indexes:
print [(m.group(),m.start(),m.end()) for m in re.finditer(r'(nn\d+)',st)][-1]
打印('nn5', 27, 30)
如果您有很多匹配项而您只想要最后一个,有时只需将字符串和模式反转即可:
If you have a lot of matches and you only want the last, sometimes it makes sense to simply reverse the string and pattern:
m=re.search(r'(\d+nn)',st[::-1])
offset=m.start(1)
print st[-m.start(1)-len(m.group(1)):-m.start(1)]
打印nn5
这篇关于如何使用正则表达式做反向搜索?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!