使用正则表达式替换QueryString值

Kri*_*s B 3 c# regex string

在C#中,我试图使用正则表达式来替换查询字符串中的值.所以,如果我有:

http://www.url.com/page.aspx?id=1

我想写一个函数,我传入url,querystring值和要替换的值.有点像:

string url = "http://www.url.com/page.aspx?id=1";
string newURL = ReplaceQueryStringValue(url, "id", "2");

private string ReplaceQueryStringValue(string url, string replaceWhat, string replaceWith)
{
    return Regex.Replace(url, "[^?]+(?:\?"+replaceWhat+"=([^&]+).*)?",replaceWith);
}
Run Code Online (Sandbox Code Playgroud)

And*_*are 10

这是一个可以完成工作的功能:

static string replace(string url, string key, string value)
{
    return Regex.Replace(
        url, 
        @"([?&]" + key + ")=[^?&]+", 
        "$1=" + value);
}
Run Code Online (Sandbox Code Playgroud)