Reputation: 58863
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.
Upvotes: 25
Views: 49806
Reputation: 500307
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)
^
matches the start of the string.[a-z]+
matches one or more lowercase letters.[*]?
matches zero or one asterisks.$
matches the end of the string.Your original regex matches exactly one lowercase character followed by one or more asterisks.
Upvotes: 30
Reputation: 324630
re.match(r"^[a-z]+\*?$", s)
The [a-z]+
matches the sequence of lowercase letters, and \*?
matches an optional literal *
chatacter.
Upvotes: 3
Reputation: 22262
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)
Upvotes: 0
Reputation: 29967
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".
Upvotes: 2