.NET regex engine returns no matches but I am expecting 8

前端 未结 1 523
星月不相逢
星月不相逢 2021-01-20 23:19

I am trying to write out a regex to get each insert line from a SQL script. When I use the .NET Regex Tester on Regex Hero I get my expected 8 matches. However, when I run this

1条回答
  •  迷失自我
    2021-01-20 23:53

    Note that toggling the "CrLf marks a line ending" setting on the Regex Hero page causes the 8 lines to stop being matched; this is a clue as to what's causing the problem.

    In your C# code, the line breaks within the literal string are encoded as a CR/LF pair ("\r\n"). The $ in the regex (that matches an end-of-line in Multiline mode) only matches the \n character. Thus, there is an extra \r character between the final comma (or semicolon) which the regex doesn't account for, and the match fails.

    Some ways you could address this problem include:

    1. Strip the carriage returns: text = text.Replace("\r\n", "\n");, or
    2. Match the carriage returns: string query = @"^\(.*?\)(,|;)\r$";

    0 讨论(0)
提交回复
热议问题