Reputation: 16723
New dad, so my eyes are tired and I'm trying to figure out why this code:
var regex = new Regex(@"(https:)?\/");
Console.WriteLine (regex.Replace("https://foo.com", ""));
Emits:
foo.com
I only have the one forward slash, so why are both being captured in the group for the replacement?
Upvotes: 3
Views: 54
Reputation: 59258
If you check what matches are generated, it becomes clear. Add this to your code:
var matches = regex.Matches("https://foo.com");
foreach (Match match in matches)
{
Console.WriteLine(match.Value);
}
And you'll see that https:/
is matched and replaced, /
is matched and replaced (because https:
is optional) and foo.com
remains.
Upvotes: 3
Reputation: 32576
In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.
Every single /
matches the regular expression pattern @"(https:)?\/"
. If you try e.g. "https://foo/./com/"
, all /
s would be removed.
Upvotes: 4