ART
ART

Reputation: 1569

String with regex comparison in python fails in python

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 ?

Upvotes: 1

Views: 39

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477200

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.

Upvotes: 2

Related Questions