我有一张 HTML:
<div class="content" itemprop="softwareVersion"> 2.3 </div>
(这是我的应用程序在 Play 商店中的版本)我想做的是使用模式匹配获取最新版本。
到目前为止我所拥有的匹配模式是:
String htmlString = "Some very long webpage string that includes the above tag"
Pattern pattern = Pattern.compile("softwareVersion\"> [^ <]*</dd");
Matcher matcher = pattern.matcher(Html);
matcher.find();
我现在如何从 htmlString 中提取 2.3
?
最佳答案
使用 JSoup xhtml 解析器
众所周知,您不应该使用正则表达式解析 xhtml,除非您知道要解析的 html 字符集。您应该使用 xhtml 解析器,例如 JSoup。所以,你可以使用这样的东西:
String htmlString = "YOUR HTML HERE";
Document document=Jsoup.parse(htmlString);
Element element=document.select("div[itemprop=softwareVersion]").first();
System.out.println(element.text());
正则表达式方法
但是,如果您想使用正则表达式,则必须使用捕获组,然后获取其内容。
String htmlString = "Some very long webpage string that includes the above tag"
Pattern pattern = Pattern.compile("softwareVersion\"> ([^ <]*)</dd");
// ^------^ Here
Matcher matcher = pattern.matcher(htmlString);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
关于java - 使用模式匹配器提取html,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32895146/