python - 在文本 block 中查找子字符串,除非它是另一个子字符串的一部分

标签 python python-2.7

我一直在寻找一种有效的方法来查找两个表达式之间的子字符串,除非该表达式是另一个表达式的一部分。

例如:

Once upon a time, in a time far far away, dogs ruled the world. The End.

如果我搜索 timeend 之间的子字符串,我会收到:

in a time far far away, dogs ruled the world. The

far far away, dogs ruled the world. The

我想忽略时间是否是很久以前的一部分。我不知道是否有一种不使用疯狂的 for 循环和 if/else 情况的 Pythonic 方法。

最佳答案

这可以在正则表达式中通过使用负向前瞻来实现

>>> s = 'Once upon a time, in a time far far away, dogs ruled the world. The End.'
>>> pattern = r'time((?:(?!time).)*)End'
>>> re.findall(pattern, s)
[' far far away, dogs ruled the world. The ']

有多个匹配:

>>> s = 'a time b End time c time d End time'
>>> re.findall(pattern, s)
[' b ', ' d ']

关于python - 在文本 block 中查找子字符串,除非它是另一个子字符串的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39581339/

相关文章:

python - 导入云存储,ImportError : No module named google. appengine.api

python - 从 matplotlib basemap 交互式获取可读(即 lng/lat)坐标?

python - 如何通过 Mechanize 传递隐藏的重新验证?

python - 随机交换列表中的两个值

python - 获取电子邮件时 python imaplib 出现内存错误

python - 如何将这个json字符串转换为dict?

python - 如何将一个简单的 python 脚本转换为基本的 webapp?

python - 用Python实现电子表格?

Python 从 csv 列表发送电子邮件

Python:如何以更简洁的形式编写?