I've tried to replace user name in Git's URL, by using Regex.replace()
.
The reason I want to use Regex.Replace
instead of string.Replace
is because I want to replace only the first occurrence.
The expected result is: "https://******:adss!#&@github.com/test/test.git"
The actual result is: "https://#32$3:adss!#&@github.com/test/test.git"
Unfortunately it's not replaced. The code as bellow:
class Program
{
private static Regex reg = new Regex(@"(?i)(http|https):\/\/(?<UserName>.*):(.*?)@.*\/");
private const string userNameGroup = "UserName";
static void Main(string[] args)
{
string url = matchRgexWithUserName("https://#32$3:adss!#&@github.com/test/test.git");
Console.WriteLine(url);
}
static string matchRgexWithUserName(string url)
{
Match match = reg.Match(url.ToString());
string username = match.Groups[userNameGroup].Value;
Regex r = new Regex(username);
url = r.Replace(url,"******",1);
return url;
}
}
this line works well:
string username = match.Groups[userNameGroup].Value;
the problem is with these lines:
Regex r = new Regex(username);
url = r.Replace(url,"******",1);
return url;
I suspect the problem is with the "$". Is there other way to overcome on it? Thanks!