0

What is the most elegant method to get the functionality of the r-prefix on string literals at run-time. That is, a string is constructed dynamically

 my_re_str = somefunction()

and then, all the backslashes need to be put back in place whenever there is a '\n', '\b' and the like. The reason for this is that the string is used to compile a regular expression in the form of

 my_re = re.compile(my_re_str)

where with constant string literals one might write

 my_re = re.compile(r"something")

Is there an elegant method to achieve this without manually replacing all backslash-ed characters?

Frank-Rene Schäfer
  • 3,182
  • 27
  • 51
  • The "r" is only used by the compiler to handle escape rules for strings typed in by us humans. There shouldn't be any need to use it on programaticly constructed strings. – tdelaney Apr 16 '17 at 02:04
  • 1
    `my_re_str.encode('unicode-escape')` does what you're asking, but I don't think it does what you actually need: actual control characters in a regex aren't a problem, and there are other characters that need to be escaped if meant literally. You might also want to look at `re.escape()`. – jasonharper Apr 16 '17 at 02:14
  • @jasonharper: That is what I was looking for! Thanks. I do not know whether the editors actually read the question. I could not find any other question on this account and why it was marked 'duplicate'. – Frank-Rene Schäfer Apr 16 '17 at 02:24

0 Answers0