1

I am trying to compare string with regex in python as follows,

#!/usr/bin/env python3

import re

str1 = "Expecting property name: line \d+ column \d+ (char \d+)"
str2 = "Expecting property name: line 3 column 2 (char 44)"

print(re.search(str1,str2))

if re.search(str1,str2) :
    print("Strings are same")
else :
    print("Strings are different")

I always get following output

None
Strings are different

I am not able to understand what is wrong here.
Can someone suggest/point me what is wrong with this ?

2
  • 1
    The brackets are interpreted. Commented Oct 16, 2018 at 14:42
  • 1
    str1 = r"Expecting property name: line \d+ column \d+ \(char \d+\)" Commented Oct 16, 2018 at 14:42

1 Answer 1

2

You need to escape the brackets, since otherwise these are seen as "grouping directives" by the regex engine:

str1 = r"Expecting property name: line \d+ column \d+ \(char \d+\)"
#                                                     ^         ^

Note that search does not mean a full match: it simply means a substring of str2 needs to match. So you might want to add ^ and $ anchors.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for reply Willem, so final regex string should be r"^Expecting property name: line \d+ column \d+ \(char \d+\)$" right ?
@AnkurTank: given you want an exact match, yes, but if 'foobar Expecting property name: line 123 column 123 \(char 123) qux other nonsense' is acceptable, then of course you can omit the anchors. It depends on what you want.
Got it.Thanks for help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.