3

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!

1 Answer 1

8

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>")
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, thanks! Is that required anytime a '\' is used? Or just in instances it is used for back-referencing?
If the first parameter is a variable, just make sure all backslashes are escaped with another backslash in front of it. The following will work as well: "<(.*)>phone</\\1>". It's just that \ has a special meaning in a regex and you'll need to escape it if you literally wish to use a \.

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.