How to match a line, ignoring the end of a new line?

I want to be able to match an entire line (hence word boundaries) with the pattern "ABC" ("ABC" is just used for convenience, I don’t want to check equality with a fixed line), so new lines are important to me. However, it turns out that a single "\ n", when placed at the end of a line, is ignored. Is there something wrong with my template?

Regex r = new Regex(@"^ABC$");
string[] strings =
{
    "ABC",//True
    "ABC\n",//True: But, I want it to say false.
    "ABC\n\n",//False
    "\nABC",//False
    "ABC\r",//False
    "ABC\r\n",//False
    "ABC\n\r"//False
};
foreach(string s in strings)
{
    Console.WriteLine(r.IsMatch(s));
}
+5
source share
1 answer

Try this (not verified):

Regex r = new Regex(@"\AABC\z");

\A= Anchor for the beginning of the line
\z= Anchor for the end of the line
^= Anchor for the beginning of the line
$= Anchor for the end of the line

+4
source

All Articles