Advertisement
Guest User

Regex to remove queries with no value

a guest
May 4th, 2015
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 1.51 KB | None | 0 0
  1. public string TrimEmptyQueries(string queryString)
  2. {
  3.     var result = Regex.Replace(queryString, @"(?<=\&|\?)([^\&\n\=]+|[^\&\n]+\=)(?>&|$)", "")
  4.                             .Trim('&');
  5.     return result == "?" ? "" : result;
  6. }
  7.  
  8. public void Main()
  9. {
  10.     var testData = new[]
  11.     {
  12.         new TestData("?foo=foo&bar&foobar&blah=blah&bleh&hi&bye&asdf&", "?foo=foo&blah=blah"),
  13.         new TestData("?foo=foo&bar=&foobar=foobar", "?foo=foo&foobar=foobar"),
  14.         new TestData("?foo=foo&bar&foobar=foobar", "?foo=foo&foobar=foobar"),
  15.         new TestData("?foo=foo&bar=bar", "?foo=foo&bar=bar"),
  16.         new TestData("?foo=foo", "?foo=foo"),
  17.         new TestData("?foo=foo&bar", "?foo=foo"),
  18.         new TestData("?foo=foo&bar=", "?foo=foo"),
  19.         new TestData("?bar&foo=foo", "?foo=foo"),
  20.         new TestData("?bar=&foo=foo", "?foo=foo"),
  21.         new TestData("?foo=", ""),
  22.         new TestData("?foo", "")
  23.     };
  24.    
  25.     foreach (var test in testData)
  26.     {
  27.         var result = TrimEmptyQueries(test.InitialValue);
  28.         Console.WriteLine("===============================================================================");
  29.         Console.WriteLine("'{0}' {1}", test.InitialValue, " should be");
  30.         Console.WriteLine("'{0}' {1}", test.ExpectedValue, " and is");
  31.         Console.WriteLine("'{0}'", result);
  32.         Console.WriteLine(result == test.ExpectedValue ? "Passed" : "Failed");
  33.     }
  34. }
  35.  
  36. public class TestData
  37. {
  38.     public string InitialValue { get; set; }
  39.     public string ExpectedValue { get; set; }
  40.    
  41.     public TestData(string initialValue, string expectedValue)
  42.     {
  43.         InitialValue = initialValue;
  44.         ExpectedValue = expectedValue;
  45.     }
  46. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement