用另一个值/令牌替换查询参数

3

我试图替换一个URL查询模式wID=xxx,其中xxx可以是数字、编号或空格,用查询wID=[[WID]]替换它(请注意,查询区分大小写)。我想知道如何实现这一点。目前,我正在使用正则表达式在URL中找到该模式,并使用Regex.Replace()进行替换,如下所示:

private const string Pattern = @"wID=^[0-9A-Za-z ]+$";
private const string Replace = @"wID=[[WID]]";
/// <summary>
/// Extension method to evaluate the url token for wid
/// </summary>
/// <param name="rawUrl">Incoming URL</param>
/// <returns>Expected URL</returns>
public string GetUrl(string rawUrl)
{
    if (string.IsNullOrWhiteSpace(rawUrl))
    {
        return string.Empty;
    }

    string result = Regex.Replace(rawUrl, Pattern, Replace);
    return result;
}

但是这并没有给我想要的输出,我猜测正则表达式模式是不正确的。有更好的方法吗? 我的问题与实现正则表达式模式以查找和替换URL查询参数值有关,我发现URI构建器在这些情况下更有帮助,可以使用它来解决这个问题。因此这是一个不同的问题。

你不应该使用正则表达式来处理这个问题,因为已经有内置的库可以帮助你解析URI。如果你提供一个样例URL,我可以给出一个无需使用正则表达式的答案。 - maccettura
你需要对 [] 进行转义吗? - maccettura
nope I don't want escaped - Darshak
可能是替换查询字符串中的项目的重复问题。 - aloisdg
显示剩余3条评论
4个回答

3
如@maccettura所说,您可以使用内置的方法。这里我们将使用HttpUtility.ParseQueryString来解析参数,然后设置值,最后替换查询。 在线试用!
public static void Main()
{
    Console.WriteLine(GetUrl("http://example.org?wID=xxx"));
}

/// <summary>
/// Extension method to evaluate the url token for wid
/// </summary>
/// <param name="rawUrl">Incoming URL</param>
/// <returns>Expected URL</returns>
public static string GetUrl(string rawUrl)
{
    if (string.IsNullOrWhiteSpace(rawUrl))
    {
        return string.Empty;
    }
    var uriBuilder = new UriBuilder(rawUrl);
    var queryString = HttpUtility.ParseQueryString(uriBuilder.Query);
    queryString.Set("wID", "[[WID]]");
    uriBuilder.Query = queryString.ToString();
    return uriBuilder.Uri.ToString();
}

输出

http://example.org/?wID=[[WID]]

如果您有另一个类似于“wID”的查询参数名称(例如“qwID”),该怎么办? - Freggar
最好先使用 .Remove("wID"),然后手动添加 wID=[[WID]]&,不幸的是你不能直接赋值 [[WID]],因为它会被转义。 - Alex K.

2

有更好的方法来完成这个任务。 可以使用NameValueCollection解析查询字符串:

 var queryStringCollection = HttpUtility.ParseQueryString(Request.QueryString.ToString());
 queryStringCollection.Remove("wID");
 string newQuery = $"{queryStringCollection.ToString()}&wID=[[WID]]";

ParseQueryString 实际上使用了一个专门的 Http 集合,当你使用 .Set 方法时会对 [ 和 ] 进行转义。 - Alex K.
好观点 @AlexK。我甚至没有注意到。我已经更新了我的答案。 - Reinder Wit

0

我会提供自己的答案,因为它更具可重用性,并且不会转义括号([]):

public static string ModifyUrlParameters(string rawUrl, string key, string val)
{
    if (string.IsNullOrWhiteSpace(rawUrl))
    {
        return string.Empty;
    }

    //Builds a URI from your string
    var uriBuilder = new UriBuilder(rawUrl);        

    //Gets the query string as a NameValueCollection
    var queryItems = HttpUtility.ParseQueryString(uriBuilder.Uri.Query);

    //Sets the key with the new val
    queryItems.Set(key, val);

    //Sets the query to the new updated query
    uriBuilder.Query = queryItems.ToString();

    //returns the uri as a string
    return uriBuilder.Uri.ToString();
}

输入为:http://example.org?wID=xxx

结果为:http://example.org/?wID=[[WID]]

在这里测试 链接


0

你不需要使用正则表达式来完成这个任务。

var index = rawUrl.IndexOf("wID=");
if (index > -1)
{
   rawUrl = rawUrl.Substring(0, index + 4) + "[[WID]]";
}

这似乎不对。为什么你要从 rawUrl 的开头开始截取子字符串?为什么它硬编码为长度为4? - maccettura

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接