C# 替换特定字符之间的字符串

C# 替换特定字符之间的字符串,c#,regex,C#,Regex,我想知道如何使用正则表达式替换两个字符之间的字符串 var oldString = "http://localhost:61310/StringtoConvert?Id=1" 预期结果=http://localhost:61310/ConvertedString?Id=1您可以使用Regex.Replacestring,string,string。因此,如果要替换a/和a?之间的子字符串,可以使用 string result = Regex.Replace(oldString, "(?<

我想知道如何使用正则表达式替换两个字符之间的字符串

var oldString  = "http://localhost:61310/StringtoConvert?Id=1"
预期结果=http://localhost:61310/ConvertedString?Id=1您可以使用Regex.Replacestring,string,string。因此,如果要替换a/和a?之间的子字符串,可以使用

string result = Regex.Replace(oldString, "(?<=\/)[^\?]*(?=\?)", "ConvertedString");

?您可以使用System.Uri类代替正则表达式,然后连接或插入新值:

private static string ReplacePath(string url, string newPath)
{
    Uri uri = new Uri(url);     
    return $"{uri.GetLeftPart(UriPartial.Authority)}/{newPath}{uri.Query}";
}
使用url调用此方法,新路径ie ConvertedString将产生以下输出:http://localhost:61310/ConvertedString?Id=1

小提琴

编辑


@埃塞尔的答案比我的好得多。不知道这个阶级的存在。将他们的答案标记为正确答案,而不是我的答案。

不需要正则表达式或字符串操作,请使用UriBuilder类

var oldString = "http://localhost:61310/StringtoConvert?Id=1";
var newuri = new UriBuilder(new Uri(oldString));
newuri.Path = "ConvertedString";
var result = newuri.ToString();

你试过什么吗?请看有关如何使用正则表达式的任何文档?可能的帮助我想感谢大家的帮助。我已经实现了私有静态字符串replacepathstringurl,字符串newPath{uriuriuri=newuriurl;返回${Uri.GetLeftPartUriPartial.Authority}/{path}{Uri.Query};},并且works@AshishParajuli使用Eser的解决方案,它的方式比我的好。同时将他们的答案标记为正确的onestring result=Regex.ReplaceoldString,http\:\/\/localhost\:61310\/\w+\?Id\=1,$1ConvertedString$3;我甚至都不知道班级的存在哈哈,这个答案比我的强!我把你的代码弄得乱七八糟,如果你想把它包括在你的答案中,请参阅谢谢maccettura。我喜欢你的方法。