0

Need to parse this String

#Login&oauth_token=theOAUTHtoken&oauth_verifier=12345

Where I just need to get oauth_token and oauth_verifier key + values, what is the simplest way to do this with Regex?

quarks
  • 33,478
  • 73
  • 290
  • 513

2 Answers2

2

This will do it, you did not specify how you wanted your data output so I seperated them with a comma.

import java.util.regex.*;

class rTest {
  public static void main (String[] args) {
    String in = "#Login&oauth_token=theOAUTHtoken&oauth_verifier=12345";
    Pattern p = Pattern.compile("(?:&([^=]*)=([^&]*))");
    Matcher m = p.matcher(in);
    while (m.find()) {
      System.out.println(m.group(1) + ", " + m.group(2));
    }
  }
}

Regular expression:

(?:           group, but do not capture:
  &           match '&'
   (          group and capture to \1:
    [^=]*     any character except: '=' (0 or more times)
   )          end of \1
   =          match '='
   (          group and capture to \2:
    [^&]*     any character except: '&' (0 or more times)
   )          end of \2
)             end of grouping

Output:

oauth_token, theOAUTHtoken
oauth_verifier, 12345
hwnd
  • 69,796
  • 4
  • 95
  • 132
0

This should work:

String s = "#Login&oauth_token=theOAUTHtoken&oauth_verifier=12345";
Pattern p = Pattern.compile("&([^=]+)=([^&]+)");
Matcher m = p.matcher(s.substring(1));
Map<String, String> matches = new HashMap<String, String>();
while (m.find()) {
    matches.put(m.group(1), m.group(2));
}
System.out.println("Matches => " + matches);

OUTPUT:

Matches => {oauth_token=theOAUTHtoken, oauth_verifier=12345}
anubhava
  • 761,203
  • 64
  • 569
  • 643