gpt4 book ai didi

python正则表达式与之间的单词匹配作为可选

转载 作者:行者123 更新时间:2023-12-01 23:54:56 24 4
gpt4 key购买 nike

我有不同的正则表达式模式,其中有很多可选部分,但它不起作用:

import re

s = 'not something useful at all'

p=re.compile(r'not (?:so)? (useful|good|correct)')

if p.search(s) != None:
print(p.search(s).group(0))
else:
print("no match")

所以,如果我执行这个,我会打印“不匹配”,但如果我将“某事”更改为“所以”,那么我会打印“不太有用”,“所以”部分是可选的,意思是如果它不存在,那么“not”和“useful”应该仍然匹配

我需要的另一种模式匹配是这样的:

import re

s = 'not random_text_inbetween useful random_text_inbetween at random_text_inbetween all'

p=re.compile(r'(not|maybe) (?:so)? (useful|good|correct) (?:at)? (?:all)?')

if p.search(s) != None:
print(p.search(s).group(0))
else:
print("no match")

编辑:好的,所以我将在这里重新表述第二部分的问题:

wiktor 提供了这个正则表达式 (not|maybe)(?:(?: so)?.*?)? (有用|好|正确)(?: at(?: all)?)?

这在此 regex 101 网站上标记以下匹配项:

Match 1
Full match 0-32 `not random_text_inbetween useful`
Group 1. 0-3 `not`
Group 2. 26-32 `useful`

但我还需要匹配/组,以防字符串中也包含一个或多个可选部分:

"not random_text_inbetween useful random_text_inbetween at random_text_inbetween all"

因此,在这个示例中,我希望为“at”、“all”创建一个组,因为它们出现在上面的文本中。

如果未找到可选部分,则不应返回这些组,而应返回“not”、“useful”等强制单词的剩余匹配项

最佳答案

好吧,我现在明白了:-)

使用这个正则表达式:

(not) (?:[^|]+) (useful) (?:[^|]+) (at)? (?:[^|]+) (all)?

我能够捕捉到我想要的东西。感谢 wiktor 帮助我并提供了这个正则表达式在线网站,这对于快速测试您的正则表达式模式非常有帮助。

关于python正则表达式与之间的单词匹配作为可选,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49110029/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com