How is \\n and \\\n interpreted by the expanded regular expression?

This is dependent on the programming language and on its string handling options.

For example, in Java strings, if you need a literal backslash in a string, you need to double it. So the regex \n must be written as "\\n". If you plan to match a backslash using a regex, then you need to escape it twice – once for Java’s string handler, and once for the regex engine. So, to match \, the regex is \\, and the corresponding Java string is "\\\\".

Many programming languages have special “verbatim” or “raw” strings where you don’t need to escape backslashes. So the regex \n can be written as a normal Python string as "\\n" or as a Python raw string as r"\n". The Python string "\n" is the actual newline character.

This can becoming confusing, because sometimes not escaping the backslash happens to work. For example the Python string "\d\n" happens to work as a regex that’s intended to match a digit, followed by a newline. This is because \d isn’t a recognized character escape sequence in Python strings, so it’s kept as a literal \d and fed that way to the regex engine. The \n is translated to an actual newline, but that happens to match the newline in the string that the regex is tested against.

However, if you forget to escape a backslash where the resulting sequence is a valid character escape sequence, bad things happen. For example, the regex \bfoo\b matches an entire word foo (but it doesn’t match the foo in foobar). If you write the regex string as "\bfoo\b", the \bs are translated into backspace characters by the string processor, so the regex engine is told to match <backspace>foo<backspace> which obviously will fail.

Solution: Always use verbatim strings where you have them (e. g. Python’s r"...", .NET’s @"...") or use regex literals where you have them (e. g. JavaScript’s and Ruby’s /.../). Or use RegexBuddy to automatically translate the regex for you into your language’s special format.

To get back to your examples:

  • \\n as a regex means “Match a backslash, followed by n
  • [\\\n] as a regex means “Match either a backslash or a newline character”.

Leave a Comment