[英]Regex two optional groups, but not just the first group
I want a regex that will capture words with two optional prefixes, but not the first one alone. 我想要一个正则表达式,可以捕获带有两个可选前缀的单词,但不能单独捕获第一个。 I'm using Python 3.6.
我正在使用Python 3.6。 It should capture
它应该捕获
cat
nicecat
bigcat
and any prefixes before those two, like 以及这两个前缀之前的任何前缀,例如
supernicecat
fatbigcat
but it should NOT capture 但它不应该捕获
fatcat
supercat
xyzcat
Here's what I have so far. 到目前为止,这就是我所拥有的。 It's not quite working.
这不是很有效。
\b(\w+)?(?:big|nice)?cat\b
You can do something like this 你可以做这样的事情
\b(?:\w*?(?:big|nice))?cat\b
Put the \\w* into the optional group. 将\\ w *放入可选组。
Here you go: 干得好:
^(?:[a-z]*(?:big|nice))?cat$
Be sure to enable multi-line flag. 确保启用多行标志。 I am assuming each entry is on its own line.
我假设每个条目都在自己的行上。
The problem with your Regex is that you made big|nice
or nothing due to the question mark. 正则表达式的问题在于,由于问号而使您变
big|nice
,什么也没做。 What I am proposing is to add [az]*
before it then add a question mark over (?:[az]*(?:big|nice))
expression in order to allow standalone cat
to match. 我建议的是在
[az]*
之前添加[az]*
,然后在(?:[az]*(?:big|nice))
表达式上添加一个问号,以允许独立的cat
匹配。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.