Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python regex match literal asterisk

Tags:

python

regex

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.

like image 629
pistacchio Avatar asked Feb 04 '12 17:02

pistacchio


People also ask

How do you match asterisk in regex?

The [a-z]+ matches one or more lowercase letters. The [*]? matches zero or one asterisks. The $ matches the end of the string.

What is the function of the asterisk (*) in regular expressions?

The asterisk has no function in regular expressions. Indicates that the preceding character may occur 1 or more times in a proper match.

How do you escape asterisk in regex?

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.

What is the difference between and * in regex?

* 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.


2 Answers

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)
  1. The ^ matches the start of the string.
  2. The [a-z]+ matches one or more lowercase letters.
  3. The [*]? matches zero or one asterisks.
  4. The $ matches the end of the string.

Your original regex matches exactly one lowercase character followed by one or more asterisks.

like image 181
NPE Avatar answered Sep 16 '22 22:09

NPE


\*? means 0-or-1 asterisk:

re.match(r"^[a-z]+\*?$", s)
like image 40
unutbu Avatar answered Sep 19 '22 22:09

unutbu