Abid A
Abid A

Reputation: 7858

Exact string match with parantheses

I've been using word boundaries to look up exact words in a string but just learned that they ignore non-word characters.

So when I look for "height" in the string "height (in stories)" I get the results I expect:

p = re.compile(r'\b%s\b' % 'height')
p.search('height (in stories)') # match

But when I look for "height (in stories)" in the string "height (in stories)" I don't get a match:

p = re.compile(r'\b%s\b' % 'height (in stories)')
p.search('height (in stories)') # no match

How can I get the parentheses recognized?

Upvotes: 1

Views: 178

Answers (3)

Has QUIT--Anony-Mousse
Has QUIT--Anony-Mousse

Reputation: 77454

When using regular expressions, you should read their syntax.

The ( and ) characters have a special meaning in regular expressions, if you want to match the characters literally, you need to escape them. Just like the dot ....

Consider using re.escape.

Upvotes: 0

quodlibetor
quodlibetor

Reputation: 8433

p = re.compile(r'\bheight \(in stories\)')

Upvotes: 1

Mark Byers
Mark Byers

Reputation: 838146

There's two problems.

  1. You need to use re.escape(text) to create a regular expression that matches the string text.
  2. There's no word boundary between a parenthesis and the end of the string.

Upvotes: 3

Related Questions