正则表达式,python:最后出现的索引。有负向后查找

0 投票
2 回答
761 浏览
提问于 2025-04-17 13:49

我需要找到一个正则表达式最后出现的位置。

在下面这句话中,我想找到最后一个句号或感叹号的位置,但如果它是短缩写的一部分(比如空格-字符-句号),就不算。

Great buy w. all amenities! Use on all cars. come on in 

我可以这样找到第一个出现的位置

t = u"Great buy w. all amenities! Use on all cars. come on in "
p = "(?<! .)([.] |! )"
i = len(re.compile(p).split(t)[0])
print i

这是“amenities”后面的感叹号。但我需要的是“cars”后面的句号。

我的缩写正则表达式可能需要调整,但关键是这个正则表达式使用了负向查找。

我尝试过使用负向前查找,但这样变得复杂,而且没有按照我想的那样工作。

2 个回答

0

你可以使用下面的代码来找到最后一次出现的 .! 的位置。

t = u"Great buy w. all amenities! Use on all cars. come on in "
i = re.search(r"((?<!\s\S)\.|!)[^.!]*$", t)
if i is not None:
    print i.start()
0

使用 finditer() 方法来遍历所有匹配的结果,然后选择最后一个匹配(通过得到的 MatchObject.start() 方法):

import re

p = re.compile("(?<! .)([.] |! )")
t = u"Great buy w. all amenities! Use on all cars. come on in "

last = None
for m in p.finditer(t):
    last = m

if last is not None:
    print m.start()

输出结果是 43

需要注意的是,你现在的正则表达式在输入的最后一个字符是标点符号时是无法正常工作的;如果把 t 改成:

t = u"Great buy w. all amenities! Use on all cars. come on in!"

结果仍然会是 43,而不是 55。你需要匹配标点符号后面跟着空格 或者 字符串的结尾:

p = re.compile("(?<! .)([.!](?:\s|$))")

这样就可以得到:

>>> import re
>>> t = u"Great buy w. all amenities! Use on all cars. come on in!"
>>> p = re.compile("(?<! .)([.!](?:\s|$))")
>>> last = None
>>> for m in p.finditer(t):
...     last = m
... 
>>> if last is not None:
...     print m.start()
... 
55

撰写回答