我在寻找一种在两个表达式之间找到子字符串的有效方法,除非该表达式是另一个表达式的一部分
例如:
Once upon a time, in a time far far away, dogs ruled the world. The End.
如果我在时间和结束之间搜索子串,我将收到:
in a time far far away, dogs ruled the world. The
或者
far far away, dogs ruled the world. The
如果时间曾经是的一部分,我想忽略它。我不知道是否有一个pythonic方法不使用crazy for循环和if/else案例
只需删除“曾经”并检查剩下的内容
这在regex中是可能的,可以使用一个负的lookahead
具有多个匹配项:
这里的典型解决方案是使用捕获和非捕获正则表达式组。由于regex交替从左到右进行解析,因此将任何异常放在规则的第一位(作为非捕获),并以要为其选择的交替结束
您可以去掉空组(当我们匹配不需要的字符串时放入的)
然后去掉结果
当你有很多要回避的短语时,这个解决方案特别有用
相关问题 更多 >
编程相关推荐