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.
The [a-z]+ matches one or more lowercase letters. The [*]? matches zero or one asterisks. The $ matches the end of the string.
The asterisk has no function in regular expressions. Indicates that the preceding character may occur 1 or more times in a proper match.
You have to double-escape the backslashes because they need to be escaped in the string itself. The forward slashes mark the start and the end of the regexp. You have to start with a forward slash and end with one, and in between escape the asterisks with backslashes.
* means zero-or-more, and + means one-or-more. So the difference is that the empty string would match the second expression but not the first.
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.
\*?
means 0-or-1 asterisk:
re.match(r"^[a-z]+\*?$", s)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With