【问题标题】:Match if string contains one substring followed by another using regex in python [duplicate]如果字符串包含一个子字符串,然后在python中使用正则表达式,则匹配另一个子字符串[重复]
【发布时间】: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)
  • 这个很好用,非常感谢!

标签: python regex


【解决方案1】:

只需要那个复杂的正则表达式,因为顺序无关紧要。如果顺序很重要,那就简单多了:

re.search(r'pattern1.*pattern2', string_to_search)

将查找pattern1,后跟pattern2

【讨论】:

  • 谢谢,加上\b,这解决了发布的问题
猜你喜欢
  • 2021-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-12
  • 2022-12-07
  • 1970-01-01
相关资源
最近更新 更多