如果正则表达式模式在此正则表达式模式之前,我如何不捕获或检测匹配
r"(?<=\s)|^)dont\s*"
这是您要用来排除匹配项的模式。它正确地使用lookbehind
"(?<=\s|^)dont"
来检查单词"dont"
之前的空格或字符串的开头。这可确保单词“dont”前面不会出现除空格或字符串开头以外的任何字符。
基本上,我想要实现的是,如果原始模式之前有一个
"dont"
,其中有一个空格 "\s"
或字符串的开头 "^"
,那么它不会检测到匹配,因此不会捕获捕获组。
import re
#example 1 with capture, because it does not match this part of the pattern (?<=\s)|^)
#input_text = "I think Idont like a lot red apples"
#example 2 not capture
input_text = "I think I dont like a lot red apples"
interests_match = re.search(r"(?:like\s*a\s*lot\s+(.+?)", input_text, flags = re.IGNORECASE)
if interests_match: print(interests_match.group(1))
每个示例的正确输出:
"red apples" #example 1
None #example 2
在这种情况下,不使用lookbehind会更容易:
r"(?:^|\s)dont\s*(?:like\s*a\s*lot\s+)(.+)"