It's best for readability (and your sanity) to avoid escaping the escapes. That's where raw strings literals come in. (Note that some languages allow delimiters, which are preferred over strings usually. But that's another section.)
They usually work the same way as this answer describes:
[A] backslash,
\
, is taken as meaning "just a backslash" (except when it comes right before a quote that would otherwise terminate the literal) -- no "escape sequences" to represent newlines, tabs, backspaces, form-feeds, and so on.
Not all languages have them, and those that do use varying syntax. C# actually calls them verbatim string literals, but it's the same thing.
pattern = r"regex"
pattern = r'regex'
The syntax here is extremely versatile. The only rule is to use a delimiter that does not appear anywhere in the regex. If you do that, no additional escaping is necessary for anything in the string. Note that the parenthesis ()
are not part of the regex:
pattern = R"delimiter(regex)delimiter";
Just use a normal string. Backslashes are ALWAYS literals.
pattern = @"regex";
Note that this syntax also allows ""
(two double quotes) as an escaped form of "
.