我一直在寻找一种有效的方法来查找两个表达式之间的子字符串,除非该表达式是另一个表达式的一部分。
例如:
Once upon a time, in a time far far away, dogs ruled the world. The End.
如果我搜索 time 和 end 之间的子字符串,我会收到:
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/