Varun Sharma
Varun Sharma

Reputation: 2759

How to extract a value from a URL query string in C#?

Possible Duplicate:
Get individual query parameters from Uri

I have got a URL like this:

http://somedomain.com/website/webpage.aspx?token=123456&language=English

My goal is to extract 123456 from it. There can only be one payment ID in the query-string parameter. What kind of regular expression can I use? I am using C# (.NET) by the way.

Thanks

Upvotes: 2

Views: 12142

Answers (4)

Andrew Cooper
Andrew Cooper

Reputation: 32576

token=(\d+) should do the trick

To cater for aplhas as well you can do either:

token=([a-zA-Z0-9+/=]+) to explicitly match on the characters you expect. This matches "token=" and then captures all following characters that match the character class, that is, a-z, A-Z, 0-9, +, / and =.

or

token=([^&#]+) to match any character except for the ones you know can finish the token. This matches "token=" and then captures all characters until the first &, # or the end of the string.

Upvotes: 6

Prabhu Murthy
Prabhu Murthy

Reputation: 9261

Use System.URI class

The Query property of the URI class returns the entire query as a string

Uri bUri = new Uri("http://somedomain.com/website/webpage.aspx
                    ?token=123456&language=English");

var query = bUri.Query.Replace("?", "");

Now query will have the string value "token=123456&language=English"

Then use LINQ to produce a Dictionary from the query attributes

var queryValues = query.Split('&').Select(q => q.Split('='))
                   .ToDictionary(k => k[0], v => v[1]);

You can then access the values as

queryValues["token"]

which will give you 123456

Upvotes: 7

maček
maček

Reputation: 77778

Do not use regex for this. C# has built-in methods for this!

var queryString = string.Join(string.Empty, url.Split('?').Skip(1));
System.Web.HttpUtility.ParseQueryString(queryString)

See more details here

Upvotes: 3

ΩmegaMan
ΩmegaMan

Reputation: 31616

Use

(?:token=)(?<TokenValue>[^&]+)

and in C# get just the value by:

myMatch.Groups["TokenValue"].Value

Upvotes: 0

Related Questions