Why $ always matches end of line

The following is a simple piece of code that demonstrates the apparently erroneous behavior of line-ending matching ("$") in .Net regular expressions. Am I missing something?

        string input = "Hello\nWorld\n";
        string regex = @"^Hello\n^World\n";  //Match
        //regex = @"^Hello\nWorld\n";  //Match
        //regex = @"^Hello$";  //Match
        //regex = @"^Hello$World$";  //No match!!!
        //regex = @"^Hello$^World$";  //No match!!!

        Match m = Regex.Match(input, regex, RegexOptions.Multiline | RegexOptions.CultureInvariant);
        Console.WriteLine(m.Success);
+3
source share
2 answers

$does not consume newline character (s). @"^Hello$\s+^World$"must match.

+6
source

$does not match the new line. It corresponds to the end of the line in which the template is applied (if multi-line mode is enabled). It makes no sense to have two ends in a row.

+1
source

All Articles