为什么我的正则表达式不工作?
问题描述:
以下代码不会打印任何内容。我究竟做错了什么? Regexp测试人员myregexp说正则表达式是正确的。为什么我的正则表达式不工作?
page = "<div id=\"foo\" class=\"foo\" style=\"background-image: url(foo.jpg); width: 320px; height: 245px\">\n" +
" <a href=\"foo\" onclick=\"return bar('foo', 'foo', {foo: bar, foo: bar}, foo)\"></a>\n" +
"</div>";
Pattern pattern = Pattern.compile("<div.*?</div>");
Matcher matcher = pattern.matcher(page);
while (matcher.find()) {
System.out.println(matcher.start() + " " + matcher.end());
}
答
缺省情况下,正则表达式中的.
与换行符不匹配。这意味着你的正则表达式不能匹配</div>
,因为它之前的换行符不匹配.
。
你应该更换你的编译行:
Pattern pattern = Pattern.compile("<div.*?</div>",Pattern.DOTALL);
但正如有人指出的意见,除了在你有过HTML的结构控制简单的情况下(没有意见,没有JavaScript等),你应该使用像JSoup这样的HTML解析器解析HTML,而不是使用正则表达式。
+0
感谢您的简单回答。 –
考虑使用jsoup解析html:https://jsoup.org/ –
[不要使用正则表达式解析HTML](http://*.com/questions/1732348/regex-match-open-tags-except -xhtml-self-contained-tags),这并不是工作的正确工具。至于你的问题,它可能不起作用,因为它是多行。 – alfasin
感谢您的咨询。我已经在使用jsoup,但是我的输入html有一些不正确的结构,所以jsoup也不起作用。 –