【发布时间】:2019-03-29 10:24:29
【问题描述】:
我正在尝试使用正则表达式在单词边界处的字符串输入中匹配一个子字符串,然后再匹配另一个子字符串。例如如果
string_1 = "I will give you a call in case I need some help in future"
如果 2 个子字符串是“will”和“in case I need”
它应该为字符串 1 返回 true
但应该为下面的字符串返回 false
string_2 = "in case I need some help I will call you"
我需要一个不区分大小写的匹配,并且只能使用正则表达式。
它也应该为以下返回 false,因为它不包含“in case I need”后跟“will”
string_3 = "I will let you know"
string_4 = "I will let you know in case we need"
我查看了Is there a regex to match a string that contains A but does not contain B,但无法确定如何向前看/向后看我的场景。该帖子涵盖了何时存在 2 个字符串,但未确定一个字符串是否跟随另一个字符串。 需要python中的解决方案,不能使用子字符串/查找等,所以需要是一个正则表达式
str = 'I will give you a call in case I need some help in future'
result = bool(re.search(r'^(?=.*\bwill\b)(?=.*\bin case I need\b).*', str))
print(result)
Above 匹配没有订单的“will”和“in case I need”。我需要执行命令,一个字符串后面跟着另一个,即“will”后面跟着“in case I need”。
【问题讨论】:
-
简单:
re.search(r'\bwill\b.*\bin case I need\b', s) -
这个很好用,非常感谢!