首先让我告诉你我来自哪里。我有一个字符串是来自网站的html代码,我使用JSOUP得到了这个。无论如何所以html都在字符串中,我可以将其打印到文本文件中。所以我试图从这段代码中获取歌曲,每首歌都是相同的"标签"
这是我打印到
的文本文件中的一行 <div class="title" itemprop="name">
Wrath
</div> </td>
在记事本中,它看起来像一条线,但是当你复制并粘贴它时,它看起来像这样。所以我想要的是中间的愤怒,所以我尝试使用其他堆栈帖子的帮助来创建一个模式:Java regex to extract text between tags
这是我的代码中与此
有关的部分Pattern p = Pattern.compile( "<div class=\"title\" itemprop=\"name\">(.+?)</div> </td>");
Matcher m = p.matcher( html );
while( m.find()) {
quote.add( m.group( 1 ));
}
运行时显示ArrayList引号中没有任何内容。这可能不起作用,因为它计算两者之间的空间。任何想法?
答案 0 :(得分:4)
您可以使用jsoup
来解析和下载HTML文档:
String site = "http://example.com/";
Document doc = Jsoup.connect(site).get();
String text doc.select("div.title").first().text();
或者只是使用XPath,如果这不起作用。正则表达式非常适合从非结构化文本中挑选数据。但是,如果您有像HTML这样的结构化文档,则可以将所有繁重的工作留给专门构建的解析器。 Java附带javax.xml.xpath
library,您可以使用它搜索文档的节点树。
假设您的文档如下所示:
<html>
<body>
<div class="title">Wrath</div>
</body>
</html>
你可以这样做来找到那个div中的文字:
XPath xpath = XPathFactory.newInstance().newXPath();
String expression = "/html/body/div[@class='title']/text()";
InputSource inputSource = new InputSource("myDocument.html");
NodeList nodes = (NodeList) xpath.evaluate(expression, inputSource, XPathConstants.NODESET);
答案 1 :(得分:0)
如果它像Perl一样解析你可能需要加倍\
Pattern p = Pattern.compile("<div class=\"title\" itemprop=\"name\">(.*?)<\\/div>");
应该是
Pattern p = Pattern.compile("<div class=\"title\" itemprop=\"name\">(.*?)<\\\\/div>");
但对于这种事情,正则表达式是错误的工具