PFranchise
PFranchise

Reputation: 6752

Issue with regex backreference in Python

I am not sure why this is not working. Perhaps I am missing something with Python regex.

Here is my regex and an example string of what I want it to match too:

    PHONE_REGEX        = "<(.*)>phone</\1>"
    EXAMPLE            = "<bar>phone</bar>"

I tested this match in isolation and it failed. I used an online regex tester and it matched. Am I simply missing something that is particular to Python regex?

Thanks!

Upvotes: 3

Views: 2557

Answers (1)

Simeon Visser
Simeon Visser

Reputation: 122376

You have to mark the string as a raw string, due to the \ in there, by putting an r in front of the regex:

m = re.match(r"<(.*)>phone</\1>", "<bar>phone</bar>")

Upvotes: 8

Related Questions