将查询参数替换为另一个值/标记

问题描述 投票:0回答:4

我试图用查询wID=xxx替换URL查询模式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构建器在这些情况下更有用,并且可以使用而不是它是不同的问题。

c# regex url
4个回答
2
投票

有更好的方法来做到这一点。看看使用NameValueCollection解析查询字符串:

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

2
投票

正如@maccettura所说,你可以使用内置的。这里我们将使用HttpUtility.ParseQueryString来解析参数然后我们设置值,最后我们替换查询。

Try it online!

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]]

0
投票

你不需要正则表达式。

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

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]]

小提琴here

© www.soinside.com 2019 - 2024. All rights reserved.