繁体   English   中英

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

[英]python regex match with words in between as optional

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

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")

因此,如果我执行此命令,则会打印“ no match”,但是如果我将“ something”更改为“ so”,那么我将打印“ not not used”,那么“ so”部分是可选的,如果不存在,则为“ not” ”和“有用”仍应匹配

我需要的另一个模式匹配是:

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)?.*?)? (useful|good|correct)(?: at(?: all)?)? (not|maybe)(?:(?: so)?.*?)? (useful|good|correct)(?: at(?: all)?)?

此标记表示此正则表达式101网站上的以下匹配项:

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

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

“不是random_text_inbetween有用 random_text_inbetween 所有的 random_text_inbetween”

所以在此示例中,我希望为“ at”,“ all”有一个分组,因为它们出现在上面的文本中。

如果未找到可选部分,则不应仅返回这些组,而仅返回诸如“ not”,“ useful”之类的必需词的其余匹配项

好吧,我现在想通了:-)

使用此正则表达式:

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

我能够捕捉到我想要的东西。 感谢wiktor为我提供的帮助,并提供了此regex在线网站,这对快速测试您的regex模式确实很有帮助。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM