I tried to match .*
with C# regular expression, and it turns out it matches any string two times: first the full string, than a second time an empty string. I expected .*
to match everything in a single match. I'm completely puzzled why that should be and how to prevent this.
Long story: I need to replace parts of filenames, with the possibility to replace unconditionally by a certain replacement string. Using an empty string as pattern will match and put the replacement after every character of the string, like it is described in Regex.Replace
. Therefor I substitute the empty string by .*
before replacement. But this turns out to execute the replacement double.
To demonstrate what is going on I used:
string input= "sometext";
string pattern= ".*";
MatchCollection matches = Regex.Matches(input, pattern);
foreach (Match match in matches) {
Console.WriteLine("[{0}]", match.Groups[0].Value); }
which yields:
[sometext]
[]
- Why does it match a second time the empty string when it already matched the whole string?
- What regex or flags do I have to use to get only a single match/replacement?