3

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?

Mister Epic
  • 16,295
  • 13
  • 76
  • 147

2 Answers2

4

Regex.Replace:

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.

AlexD
  • 32,156
  • 3
  • 71
  • 65
3

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.

Thomas Weller
  • 55,411
  • 20
  • 125
  • 222