Reputation: 13758
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
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
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