Dave31415
Dave31415

Reputation: 2946

Why does this python re match?

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

Answers (5)

ThiefMaster
ThiefMaster

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

Mark Ransom
Mark Ransom

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

Moishe Lettvin
Moishe Lettvin

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

wkl
wkl

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

kojiro
kojiro

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

Related Questions