问题
Given the following string:
s = 'abcdefg*'
How can I match it or any other string only made of lowercase letters and optionally ending with an asterisk? I thought the following would work, but it does not:
re.match(r"^[a-z]\*+$", s)
It gives None and not a match object.
回答1:
How can I match it or any other string only made of lowercase letters and optionally ending with an asterisk?
The following will do it:
re.match(r"^[a-z]+[*]?$", s)
- The
^matches the start of the string. - The
[a-z]+matches one or more lowercase letters. - The
[*]?matches zero or one asterisks. - The
$matches the end of the string.
Your original regex matches exactly one lowercase character followed by one or more asterisks.
回答2:
\*? means 0-or-1 asterisk:
re.match(r"^[a-z]+\*?$", s)
回答3:
re.match(r"^[a-z]+\*?$", s)
The [a-z]+ matches the sequence of lowercase letters, and \*? matches an optional literal * chatacter.
回答4:
Try
re.match(r"^[a-z]*\*?$", s)
this means "a string consisting zero or more lowercase characters (hence the first asterisk), followed by zero or one asterisk (the question mark after the escaped asterisk).
Your regex means "exactly one lowercase character followed by one or more asterisks".
回答5:
You forgot the + after the [a-z] match to indicate you want 1 or more of them as well (right now it's matching just one).
re.match(r"^[a-z]+\*+$", s)
来源:https://stackoverflow.com/questions/9142736/python-regex-match-literal-asterisk