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