Help with regex c#
I have an input string:
access_token=f34b46f0f109d423sd4236af12d1bce7f10df108ec2183046b8f94641ebe&expires_in=0&user_id=37917395
Source code:
Regex regex = new Regex("access_token=([^&]+)");
MatchCollection matches;开发者_如何学编程
matches = regex.Matches(webBrowser1.SaveToString());
if (matches.Count != 0 || access_token != string.Empty) {
webBrowser1.IsEnabled = false;
webBrowser1.IsHitTestVisible = false;
if (access_token == string.Empty)
access_token = matches[0].Value.Substring(13);
I get the access token but I also have to match the user_id. How can I get it?
Please help me, I'm not good at this.
Assuming your string is in input
This will set the variables accessToken and userId. If there is no match the values will be null.
Regex regex=new Regex("(?:access_token=(?<access>[^&]+))|(?:user_id=(?<userid>[^&]+))");
var accessToken=regex.Matches(input).OfType<Match>().Select(m=>m.Groups["access"]).Where(g=>g.Success).Select(g=>g.Value).FirstOrDefault();
var userId=regex.Matches(input).OfType<Match>().Select(m=>m.Groups["user_id"]).Where(g=>g.Success).Select(g=>g.Value).FirstOrDefault();
I usually have an extension method defined to reduce typing for me
public static string GetGroup(this MatchCollection matches,string group name) {
return matches.OfType<Match>().Select(m=>m.Groups[name]).Where(g=>g.Success).Select(g=>g.Value).FirstOrDefault();
}
This allows me to do:
var matches=regex.Matches(input);
var accessToken=matches.GetGroup("access");
var userId=matches.GetGroup("user_id");
string input = @"access_token=f34b46f0f109d423sd4236af12d1bce7f10df108ec2183046b8f94641ebe&expires_in=0&user_id=37917395";
var result = Regex.Match(input, @"access_token=([^&]+).*?user_id=([^&]+)");
var access_token = result.Groups[1].Value;
var user_id = result.Groups[2].Value;
精彩评论