Regular expression capturing more than expected

New daddy 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", ""));

      

Outputs:

foo.com

I only have one forward slash, so why were they both grouped for replacement?

+3


source to share


2 answers


Regex.Replace :

All strings that match the regular expression pattern with the specified replacement are replaced in the specified input line.



Each /

matches a regular expression pattern @"(https:)?\/"

. If you try eg. "https://foo/./com/"

, everything /

will be deleted.

+4


source


If you check what matches will be 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 will see what is https:/

matched and replaced, /

matched and replaced (since it https:

is optional) and foo.com

remains.

+4


source







All Articles