需要解析此String
#Login&oauth_token=theOAUTHtoken&oauth_verifier=12345
我只需要获取oauth_token
和oauth_verifier
键+值,使用Regex执行此操作的最简单方法是什么?
答案 0 :(得分: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
答案 1 :(得分:0)
这应该有效:
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);
<强>输出:强>
Matches => {oauth_token=theOAUTHtoken, oauth_verifier=12345}