0

需要解析这个字符串

#Login&oauth_token=theOAUTHtoken&oauth_verifier=12345

我只需要获取oauth_tokenoauth_verifier键+值,使用正则表达式执行此操作的最简单方法是什么?

4

2 回答 2

2

这样就可以了,您没有指定您想要的数据输出方式,所以我用逗号分隔它们。

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));
    }
  }
}

正则表达式:

(?:           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

输出:

oauth_token, theOAUTHtoken
oauth_verifier, 12345
于 2013-08-18T18:05:09.257 回答
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}
于 2013-08-18T17:26:49.797 回答