0

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.

2
  • You need to match user_id also? Commented Jul 27, 2011 at 10:25
  • does the order matter? could user_id come first? Commented Jul 27, 2011 at 10:40

2 Answers 2

3

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");
Sign up to request clarification or add additional context in comments.

2 Comments

Could you be more specific as to how it doesn't work, I've tested this with linqpad and your supplied string and it works fine?
I'm guessing that you didn't have a reference to System.Linq so the OfType and Select extension methods failed
2
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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.