gpt4 book ai didi

c# - 使用正则表达式替换 QueryString 值

转载 作者:行者123 更新时间:2023-11-30 13:29:23 25 4
gpt4 key购买 nike

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

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

我想编写一个函数,在其中传递 url、查询字符串值和要替换的值。类似的东西:

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);
}

最佳答案

这是一个可以完成这项工作的函数:

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

关于c# - 使用正则表达式替换 QueryString 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1423622/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com