我同意正则表达式很简单,但我真的不明白为什么它不能找到和提取数据。另外,我对 Java 的经验很少,可能是这个原因。
方法一
String access_token = Utils.extractPattern(url, "access_token=([a-z0-9]+)&");
网址类似于 https://oauth.vk.com/blank.html#access_token=abcedefasdasdasdsadasasasdads123123&expires_in=0&user_id=1111111111
工具
public static String extractPattern(String string, String pattern) {
Pattern searchPattern = Pattern.compile(pattern);
Matcher matcher = searchPattern.matcher(string);
Log.d("pattern found - ", matcher.matches() ? "yes" : "no");
return matcher.group();
}
为什么失败并显示 java.lang.IllegalStateException: No successful match so far
?
您需要使用Matcher
类的find()
方法来检查是否找到了Pattern
。 Here's文档:
Attempts to find the next subsequence of the input sequence that
matches the pattern.
This method starts at the beginning of this
matcher's region, or, if a previous invocation of the method was
successful and the matcher has not since been reset, at the first
character not matched by the previous match.
If the match succeeds then more information can be obtained via the
start, end, and group methods.
下面应该可以工作:
public static String extractPattern(String string, String pattern) {
Pattern searchPattern = Pattern.compile(pattern);
Matcher matcher = searchPattern.matcher(string);
if(matcher.find()){
System.out.println("Pattern found");
return matcher.group();
}
throw new IllegalArgumentException("Match not found");
}