Can';使用Python正则表达式无法获得预期结果

Can';使用Python正则表达式无法获得预期结果,python,regex,Python,Regex,我还尝试了[a-zA-Z]{2,}-\d+,但结果相同 def verify_commit_text(tags): for line in tags: if re.match('^NO-TIK',line): return True elif re.match('^NO-REVIEW', line): return True elif re.match('[a-zA-Z]-[0-9][0-9]

我还尝试了
[a-zA-Z]{2,}-\d+
,但结果相同

def verify_commit_text(tags):
    for line in tags:
        if re.match('^NO-TIK',line):
            return True
        elif re.match('^NO-REVIEW', line):
            return True
        elif re.match('[a-zA-Z]-[0-9][0-9]', line):
            return True
        else:
            return False
if __name__ == '__main__':
    commit_text_verified = verify_commit_text(os.popen('hg tip --template "{desc}"'));
    #commit_text_verified = verify_commit_text(os.popen('hg log -r $1  --template "{desc}"'));
    if (commit_text_verified):
        sys.exit(0)
    else:
        print >> sys.stderr, ('[obey the rules!]')
        sys.exit(1);
如果我使用文本“JIRA-1234”中的正则表达式:

 elif re.match('[a-zA-Z]-[0-9][0-9]', line):
似乎不起作用,我得到:

[obey the rules!]

在stdout上。

正则表达式完全按照您指定的方式工作。。它正在搜索1字符和1数字。你可能想要像这样的东西

re.match(r'[a-zA-Z]+-\d+\Z', line)

此外,始终在正则表达式字符串前面加上“r”,如上所述。否则它会咬你。

因为你想匹配一个或多个字母和数字,你需要像这样使用
+

r'[a-zA-Z]+-\d+'
您还可以使用
{}
指定一定数量的字母(例如):

r'[a-zA-Z]{2,}-\d{4}'
这里,
{2,}
表示2个或更多,
{4}
表示4,
{3}
表示0-3,
{1,5}
表示1-5,包括1-5