C# remove empty url parameters regex

前端 未结 3 1134
轻奢々
轻奢々 2021-01-25 07:09

I am trying to remove empty url type parameters from a string using C#. My code sample is here.

    public static string test ()
    {
        string parameters          


        
相关标签:
3条回答
  • 2021-01-25 07:49

    The results of the Regex replace is not returned by the function. The function returns the variable "parameters", which is never updated or changed.

    string parameters = "one=aa&two=&three=aaa&four=";
    ...
    string result = rgx.Replace(parameters, replacement);
    return parameters;
    ....
    

    Perhaps you meant

    return results;
    
    0 讨论(0)
  • 2021-01-25 07:50

    Regex:

    (?:^|&)[a-zA-Z]+=(?=&|$)
    

    This matches start of string or an ampersand ((?:^|&)) followed by at least one (english) letter ([a-zA-Z]+), an equal sign (=) and then nothing, made sure by the positive look-ahead ((?=&|$)) which matches end of string or a new parameter (started by &).

    Code:

    public static string test ()
    {
        string parameters = "one=aa&two=&three=aaa&four=";
        string pattern = "(?:^|&)[a-zA-Z]+=(?=&|$)";
        string replacement = "";
        Regex rgx = new Regex(pattern);
        string result = rgx.Replace(parameters, replacement);
    
        return result;
    }
    
    public static void Main(string[] args)
    {
        Console.WriteLine(test());
    }
    

    Note that this also returns the correct variable (as pointed out by Joel Anderson)

    See it live here at ideone.

    0 讨论(0)
  • 2021-01-25 07:57

    You absolutely do not need to roll your own Regex for this, try using HttpUtility.ParseQueryString():

    public static string RemoveEmptyUrlParameters(string input)
    {
        var results = HttpUtility.ParseQueryString(input);
    
        Dictionary<string, string> nonEmpty = new Dictionary<string, string>();
        foreach(var k in results.AllKeys)
        {
            if(!string.IsNullOrWhiteSpace(results[k]))
            {
                nonEmpty.Add(k, results[k]);
            }
        }
    
        return string.Join("&", nonEmpty.Select(kvp => $"{kvp.Key}={kvp.Value}"));
    }
    

    Fiddle here

    0 讨论(0)
提交回复
热议问题