Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression capturing more than expected

Tags:

c#

regex

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?

like image 858
Mister Epic Avatar asked Apr 19 '26 02:04

Mister Epic


1 Answers

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.

like image 184
AlexD Avatar answered Apr 20 '26 15:04

AlexD