Reputation: 2759
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
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
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
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)
Upvotes: 3
Reputation: 31616
Use
(?:token=)(?<TokenValue>[^&]+)
and in C# get just the value by:
myMatch.Groups["TokenValue"].Value
Upvotes: 0