Within an ERE, a backslash character (\, \a, \b, \f, \n,
\r, \t, \v) is considered to begin an escape sequence.
Then I see \\n and [\\\n], I can guess though both \\n and [\\\n] here means \ followed by new line, but I’m confused by the exact process to interpret such sequence as how many \s are required at all?
UPDATE
I don’t have problem understanding regex in programing languages so please make the context within the lexer.
[root@ ]# echo "test\
> hi"
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
\nmust 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
\ncan be written as a normal Python string as"\\n"or as a Python raw string asr"\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\disn’t a recognized character escape sequence in Python strings, so it’s kept as a literal\dand fed that way to the regex engine. The\nis 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\bmatches an entire wordfoo(but it doesn’t match thefooinfoobar). 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:
\\nas a regex means “Match a backslash, followed byn“[\\\n]as a regex means “Match either a backslash or a newline character”.