2011-09-20 75 views
-2

我也試過[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!] 

在標準輸出。

回答

2

正則表達式的工作完全按照您指定它。它是尋找性格和位。你可能想是這樣

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

此外,始終以「R」如上面的前綴正則表達式的字符串。或者它會咬你。

1

既然你想匹配一個或多個字母和數字,你需要使用+這樣的:

r'[a-zA-Z]+-\d+' 

您還可以{}指定一定數量的字母(例如):

r'[a-zA-Z]{2,}-\d{4}' 

這裏,{2,}指2個或更多,{4}表示正好4,{,3}裝置0-3,並且{1,5}裝置1-5的包容性。