1

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 = "one=aa&two=&three=aaa&four=";
        string pattern = "&[a-zA-Z][a-zA-Z]*=&";
        string replacement = "";
        Regex rgx = new Regex(pattern);
        string result = rgx.Replace(parameters, replacement);

        return parameters;
    }

    public static void Main(string[] args)
    {
        Console.WriteLine(test());
    }

I tried the code in rextester

output: one=aa&two=&three=aaa&four=

expected output: one=aa&three=aaa

2
  • Try (?:^|&)[a-zA-Z]+=(?=&|$) instead. Commented Jan 25, 2018 at 14:55
  • 3
    Why use Regex? You could just use HttpUtility.ParseQueryString Commented Jan 25, 2018 at 14:56

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

1 Comment

thank you that worked, will accept your answer when it will be available
0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.