如何解析分支名称的版本号

时间:2019-05-26 10:01:06

标签: python regex

鉴于分支名称为release-1.0release-0.4alpharelease-12.02,我想使用python 3 regex表达式来解析版本号。

我拥有的是:

#!/usr/bin/python3

import re; 
import sys

arg = sys.argv[1]
regex = r'(?<=(^release-))\d+.\d+(alpha)?$'

match = re.match(regex, arg)

if match:
    print(match.group())
else:
    print('Branch "{}" is not valid release branch.'.format(arg))
    sys.exit(1)

但这无法匹配任何尝试的名称:

$ ./scripts/bin/get-version-number-from-branch release-1.0
Branch "release-1.0" is not valid release branch.
$ ./scripts/bin/get-version-number-from-branch release-1.0alpha
Branch "release-1.0alpha" is not valid release branch.

我最初是在https://pythex.org/https://regex101.com/上进行构建和测试的。

有什么想法我想念的吗?

1 个答案:

答案 0 :(得分:1)

https://docs.python.org/3/howto/regex.html#match-versus-search

使用search代替match作为

#!/usr/bin/python3

import re; 
import sys

arg = sys.argv[1]
regex = r'(?<=(^release-))\d+.\d+(alpha)?$'

match = re.search(regex, arg)

if match:
    print(match.group())
else:
    print('Branch "{}" is not valid release branch.'.format(arg))
    sys.exit(1)