如何构造一个正则表达式模式,将以下示例与三个捕获组相匹配,如下所示:
示例 | grp1 | grp2 | grp3 |
---|---|---|---|
foo:bar-alpha | 富 | 酒吧 | 阿尔法 |
foo:bar-beta | 富 | 酒吧 | 测试版 |
富:酒吧 | 富 | 酒吧 |
grp3 是可选的
尝试:
(.*):(.*)(-(alpha|beta))
仅匹配前两种情况,但我希望最后一组是可选的..
(.*):(.*)(-(alpha|beta))?
添加 ?
量词匹配所有 3 个,但允许第二组捕获所有内容
我正在使用Python正则表达式
注意:我的实际输入是保密的。例子很有代表性。
以下正则表达式为您提供了正确的组示例:
^([^:]+):([^-]+)(?:-(.+))?$
它使用非捕获组 (
(?:...)
) 使第三组可选,而不引入第四组。
按照支持的方式拆分并评论使用
re.VERBOSE
时,所有部分均已解释:
r = re.compile("""
^ # assert beginning of string.
([^:]+) # first group: everything up to next colon.
: # literal colon as separator.
([^-]+) # second group: everything until a hyphen appears:
# now if there's no third part, that's it.
# if there is no hyphen, group 2 will go to the end
# of the line.
(?: # non-capturing group to make this part optional.
- # a literal hyphen.
(.+) # anything until the end.
)? # make this group optional.
$. # assert end of string.
""", re.VERBOSE)
我假设您的所有三个组(如果存在)的长度都需要至少为 1,这意味着
foo:bar-
、:bar
和 asdf:-qwer
都是无效输入。
如果其中任何一个不符合您的要求,请详细说明,并可能为您的问题添加其他示例或解释。