Python regular expression matches literal asterisk

Given the following line:

s = 'abcdefg*' 

How can I match it or any other string consisting only of lowercase letters and possibly ending with an asterisk? I thought the following would work, but it is not:

 re.match(r"^[az]\*+$", s) 

It gives None , not an object of correspondence.

+6
source share
5 answers

How can I match it or any other string consisting of only lowercase letters and optionally ending with an asterisk?

This will do the following:

 re.match(r"^[az]+[*]?$", s) 
  • ^ matches the beginning of a line.
  • [az]+ matches one or more lowercase letters.
  • [*]? matches zero or one asterisk.
  • $ matches the end of a line.

Your original regular expression matches only one lowercase character, followed by one or more asterisks.

+13
source

\*? means asterisk 0-or-1:

 re.match(r"^[az]+\*?$", s) 
+4
source
 re.match(r"^[az]+\*?$", s) 

[az]+ matches the sequence of lowercase letters, and \*? matches the optional literal * chatact.

+2
source

Try

 re.match(r"^[az]*\*?$", s) 

this means "a string consisting of zero or more lowercase characters (hence the first asterisk), followed by zero or one asterisk (question mark after an escaped asterisk).

Your regular expression means "exactly one lowercase character followed by one or more asterisks."

+1
source

You forgot + after matching [az] to indicate that you want 1 or more of them (now this only matches one).

  re.match(r"^[az]+\*+$", s) 
0
source

Source: https://habr.com/ru/post/907652/


All Articles