4

Normally you would put an r in front of the string to make it raw, but how to do this with a variable (string)?

This is what I tried so far:

import re
var = "++"
re.search(r"++", "++")      # also does not work
re.search(var, "++")        # fails
re.search(r(var), "++")     # fails
re.search(r + var, "++")    # fails
re.search("r" + var, "++")  # fails
8
  • See this. Commented Sep 15, 2013 at 12:47
  • Unfortunately it is not possible, the string comes from a file and I can't assign because of that? Commented Sep 15, 2013 at 12:48
  • 1
    Raw strings are just ways to put characters into strings that would otherwise be interpreted as escape sequences. If you're reading from a file, then it doesn't apply - what exactly is the problem? Commented Sep 15, 2013 at 12:50
  • re.search(r"++", "++") does not work for me (python 2.7.5), as expected --- becuase "++" is not a valid regex. + is a special symbol, and you need to escape it if you want to match it. Commented Sep 15, 2013 at 12:52
  • @Bogdan You are correct, this also does not work. Commented Sep 15, 2013 at 12:54

2 Answers 2

6

Use the re.escape() function for this.

>>> import re
>>> var = "++"
>>> re.search(re.escape(var), '++')
<_sre.SRE_Match object at 0x02B36B80>
Sign up to request clarification or add additional context in comments.

Comments

2

This doesn't make sense, as r instructs the interpreter on how to interpret a string you put in a source code file. In your example you would have var = r"++", and then you can use var. It does not modify string contents, it's just a way of saying what do you want to put in a string. So var = "\\n" is equivalent to var = r"\n" - var variable will contain exactly the same bytes and from then on, you can't change them with any modifiers. These modifiers exist and have any effect only during parsing source code file stage - when the program is running, in the compiled byte code there is no trace of them.

Comments

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.