PascalVKooten
PascalVKooten

Reputation: 21481

Regex python attaching raw to string variables

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

Upvotes: 4

Views: 3934

Answers (2)

hwnd
hwnd

Reputation: 70750

Use the re.escape() function for this.

>>> import re
>>> var = "++"
>>> re.search(re.escape(var), '++')
<_sre.SRE_Match object at 0x02B36B80>

Upvotes: 6

BartoszKP
BartoszKP

Reputation: 35921

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.

Upvotes: 2

Related Questions