pistacchio
pistacchio

Reputation: 58863

Python regex match literal asterisk

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

Answers (5)

NPE
NPE

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

Upvotes: 30

Niet the Dark Absol
Niet the Dark Absol

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

Wes Hardaker
Wes Hardaker

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

Daniel Hepper
Daniel Hepper

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

unutbu
unutbu

Reputation: 879411

\*? means 0-or-1 asterisk:

re.match(r"^[a-z]+\*?$", s)

Upvotes: 7

Related Questions