模式和匹配器在Android中是如此奇怪

时间:2014-01-09 13:36:52

标签: android regex

本规范不起作用:

String description = Pattern.compile("<div.*?>(.*?)</div>", Pattern.DOTALL).matcher(html).group(1);

本准则正在运作:

Pattern pdescription = Pattern.compile("<div.*?>(.*?)</div>", Pattern.DOTALL);
Matcher mdescription = pdescription.matcher(html);
if (mdescription.find()) {
     String description = mdescription.group(1);
}

为什么我需要声明两个对象? Logcat写道:

01-09 21:33:06.741: E/AndroidRuntime(1734): FATAL EXCEPTION: Thread-150    
01-09 21:33:06.741: E/AndroidRuntime(1734): java.lang.IllegalStateException: No successful match so far    
01-09 21:33:06.741: E/AndroidRuntime(1734):     at java.util.regex.Matcher.ensureMatch(Matcher.java:607)    
01-09 21:33:06.741: E/AndroidRuntime(1734):     at java.util.regex.Matcher.group(Matcher.java:358)    
01-09 21:33:06.741: E/AndroidRuntime(1734):     at com.ibelieve.news.SearchEngine.Baidu.GetNews(Baidu.java:45)    
01-09 21:33:06.741: E/AndroidRuntime(1734):     at com.ibelieve.news.MainActivity$2$1.run(MainActivity.java:52)    
01-09 21:33:06.741: E/AndroidRuntime(1734):     at java.lang.Thread.run(Thread.java:856)

1 个答案:

答案 0 :(得分:0)

在第一个例子中,你还没有找到任何东西。

As stated in the docs for group:

  

IllegalStateException - 如果尚未尝试匹配,或者上一次匹配操作失败