Reputation: 2946
Can someone explain this weird behavior of python re? Obviously the string 'test' does not contain either 'Bid' or 'Ask'. Why is this matching?
import re
pat=r'[Bid|Ask]'
reg=re.compile(pat)
if reg.search('test'): print "matched!"
... matched!
Upvotes: 1
Views: 396
Reputation: 318498
[...]
defines a character class, matching any character listed inside. What you wanted is par = r'(Bid|Ask)'
.
However, you should not use regex for this at all, do the following instead:
if whatever in ('Bid', 'Ask'):
# it's one of these two
else:
# it isn't
If you need to perform a substring check (thanks @agf):
if any(word in whatever for word in ('Bid', 'Ask')):
# one of the words is in the sting whatever
Upvotes: 10
Reputation: 308130
I think you want ()
instead of []
. You've told it to match on any single character in the group Bid|Ask
and the string contains s
.
Upvotes: 1
Reputation: 8471
Your regex is searching for the set of characters B,i,d,|,A,s,k. 's' matches inside 'test'.
You should omit the brackets.
Also if you don't want to match strings like "Askify" you'll need to refine your regex a little more.
Upvotes: 0
Reputation: 79901
[...]
is the character class matcher, which means it will match any character in the set.
You probably wanted alternation, like this: r'(Bid|Ask)'
.
Upvotes: 5
Reputation: 77089
Your regular expression is simply a character set containing the characters 'B', 'i', 'd', '|', 'A', 's', and 'k'. There is an 's' in 'test'.
What you probably meant was "(Bid|Ask)"
Upvotes: 2