yasar
yasar

Reputation: 13758

How to match '-' literally inside [..] in regular expression

I am trying to match a '-' inside a [..] block using regular expressions in python, but, I am not sure how to make that happen, since '-' denotes ranges in that block.

Edit: my failing regex:

regex = re.compile("^[0-9+-*/]+$")

Upvotes: 3

Views: 438

Answers (2)

Jared Ng
Jared Ng

Reputation: 5071

Just place it at the beginning of the [] (character class):

regex = re.compile("^[-0-9+*/]+$")

Why does it work?

When you place the hyphen at the beginning of the character class, most regular expression engines are intelligent enough to realize that you mean a literal hyphen (since you can't indicate a range without an beginning).

Upvotes: 6

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799150

From the docs:

If you want to include a ']' or a '-' inside a set, precede it with a backslash, or place it as the first character.

Upvotes: 9

Related Questions