简体   繁体   English

regex.replace不适用于带有“ $”的模式-C#

[英]regex.replace does not working in pattern with “$” - c#

I've tried to replace user name in Git's URL, by using Regex.replace() . 我试图通过使用Regex.replace()替换Git URL中的用户名。

The reason I want to use Regex.Replace instead of string.Replace is because I want to replace only the first occurrence. 我想使用Regex.Replace而不是string.Replace的原因是因为我只想替换第一个匹配项。

The expected result is: "https://******:adss!#&@github.com/test/test.git" The actual result is: "https://#32$3:adss!#&@github.com/test/test.git" 预期结果为: "https://******:adss!#&@github.com/test/test.git"实际结果为: "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! 谢谢!

It doesn't work, because $ is a special character in regex. 它不起作用,因为$是正则表达式中的特殊字符。

To solve the problem, you can put everything before UserName and after it into groups too: 要解决此问题,您也可以将所有内容放在UserName之前和之后,也可以将其分组:

Regex reg = new Regex(@"(?<firstPart>(?i)(http|https):\/\/)(?<UserName>.*)(?<secondPart>:(.*?)@.*\/)");

Then you can use Replace to combine firstPart , "******" and secondPart - without UserName : 然后,您可以使用Replace组合firstPart"******"secondPart不使用UserName

string result = reg.Replace(url, "${firstPart}******${secondPart}");

Basically, you match the url to a {firstPart}{UserName}{secondPart} pattern and replace it with {firstPart}******{secondPart} (removing the UserName ). 基本上,您将网址与{firstPart}{UserName}{secondPart}模式匹配,然后将其替换为{firstPart}******{secondPart} (删除UserName )。

Using Regex.Replace that way is the wrong way to go about this. 使用Regex.Replace这种方法是错误的方法。 Once you know the username, you can use a regular string replace: 一旦知道用户名,就可以使用常规字符串替换:

url = url.Replace("://" + username, "://" + "*****");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM