Can't get expected result with Python regex [closed]
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
开发者_C百科 Improve this questionI also tried [a-zA-Z]{2,}-\d+
but with the same results
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);
if i use a text "JIRA-1234"
the regex in :
elif re.match('[a-zA-Z]-[0-9][0-9]', line):
does not seem to work and i get:
[obey the rules!]
on stdout.
The regex is working exactly as you've specified it .. it is searching for 1 character and 1 digit. You probably want something like
re.match(r'[a-zA-Z]+-\d+\Z', line)
Further, always prefix regular expression strings with an 'r' as in the above. Or it will bite you.
Since you want to match one or more letters and numbers, you need to use the +
like this:
r'[a-zA-Z]+-\d+'
You can also specify a certain number of letters (for example) with {}
:
r'[a-zA-Z]{2,}-\d{4}'
Here, {2,}
means 2 or more, {4}
means exactly 4, {,3}
means 0-3, and {1,5}
means 1-5 inclusive.
精彩评论