While answering this question C# Regex Replace and * the point was raised as to why the problem exists. When playing I produced the following code:
string s = Regex.Replace(".A.", "\w*", "B");
Console.Write(s);
This has the output: B.BB.B
I get that the 0 length string is match before and after the . character, but why is A replaced by 2 Bs.
I could understand B.BBB.B as replacing zero-length strings either side of A or B.B.B
But the actual result confuses me – any help appreciated.
Or as AakashM has put it:
Why is Regex.Matches("A", "\w*").Count equal to 2, not 1 or 3 ?
because \w* is a greedy regex and it tries to find biggest sequence. So it matches
"nothing"before dot, then"nothing"Abetween two dots then"nothing"before second dot and finally"nothing"after the second dot.