Regular Expressions Escaping Raw String Literals


Example

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.


Python

pattern = r"regex"
pattern = r'regex'

C++ (11+)

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";

VB.NET

Just use a normal string. Backslashes are ALWAYS literals.

C#

pattern = @"regex";

Note that this syntax also allows "" (two double quotes) as an escaped form of ".