C# remove empty url parameters regex

前端 未结 3 1136
轻奢々
轻奢々 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: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.

提交回复
热议问题