0

Possible Duplicate:
How to parse a query string into a NameValueCollection in .NET

I have input as

https://localhost:8181/PortalSite/View/CommissionStatement.aspx?status=commission&quarter=1;

Output needed

status=commission

How to do in C#(preferably regular expression or something else)..

My solution

var res = src.Split('?')[1].Split('=')[1].Split["&"][0];

but failing in Split["&"]

Community
  • 1
  • 1
user1025901
  • 1,849
  • 4
  • 21
  • 28

3 Answers3

6

Note that in cases like this, the common fallacy is to just put together some string handling function that cannot deal with the full possible spec of input. In your case, there are a lot of valid URLs that are actually rather hard to handle/parse correctly. So you should stick to the already implemented, proven classes.

Thus, I would use the System.Uri class to consume the URL string. The part of the URL you're actually trying to access is the so called "query", which is also a property of the Uri instance. The query itself can easily and correctly be accessed as its individual key-value parts using the System.Web.HttpUtility.ParseQueryStringMethod() (you need to add System.Web.dll to your project's references and make sure you're not using the .NET 4 client profile for your application, as that will not include this assembly).

Example:

Uri u = new Uri("https://localhost:8181/PortalSite/View/CommissionStatement.aspx?status=commission&quarter=1;");
Console.WriteLine(u.Query); // Prints "status=commission&quarter=1;"

var parameters = HttpUtility.ParseQueryString(u.Query);
Console.WriteLine(parameters["status"]); // Prints "commission"

Once you have the "parameters" you could also iterate over them, search them, etc. YMMV.

If you require the output you show in your question, thus know that you always need the first parameter of the query string (and are not able to look it up by name as I show above), then you could use the following:

string key = parameters.GetKey(0);
Console.WriteLine(key + "=" + parameters[key]); // Prints "status=commission"
Christian.K
  • 47,778
  • 10
  • 99
  • 143
6

If what you're going for is guaranteed to be a URL with a query string, I would recommend the HttpUtility.ParseQueryStringMethod.

var result = HttpUtility.ParseQueryString(new Uri(src).Query);
casperOne
  • 73,706
  • 19
  • 184
  • 253
2

You could use the following regex: status=(\w*) But I think there are better alternatives like using HttpUtility.ParseQueryStringMethod.

Oleks
  • 31,955
  • 11
  • 77
  • 132
Daniel
  • 920
  • 7
  • 19