code_assassin
code_assassin

Reputation: 133

Django CharField storing newline

I have a CharField storing user input, including things like "\n" (literally, not by hitting "enter"), which is later used for parsing text with regular expressions. When I fetch the model from the database, however, comparing the value to '\n' fails - it's equal to '\n' instead. How do I unescape it? I do escape it later before insertion into the regular expression, since the field may contain e.g. "*", which I want to be interpreted literally. I tried mark_safe but no luck.

Upvotes: 2

Views: 985

Answers (1)

code_assassin
code_assassin

Reputation: 133

OK I figured it out, thanks to the answers in this question: Python Replace \\ with \

Basically, I needed to do something like that:

separator = processor.separator.decode('string_escape')  # Decode
expr = r"<something>" + re.escape(separator)  # Escape for the regular expression

Upvotes: 1

Related Questions