java - 在 HTML 标签之间提取数据

标签 java html regex

我的 HTML 页面如下所示:

<htm>

<section class="posts">

      <script type="application/ld+json">
        {
          "url": "http://schema.org",
          "title": "some Title"
        }
      </script>


    <article class="post">
</html>

我想提取 <script type="application/ld+json"> 之间的数据和 </script> .我已尝试使用以下代码,但它不起作用。

Pattern pattern = Pattern.compile("<script type=\"application\\/ld\\+json\">(.*?)</script>");
Matcher matcher = pattern.matcher(str);
    while (matcher.find()) {
       System.out.println(matcher.group(1));
    }

我做错了什么吗? 谢谢。

最佳答案

从上面的 HTML 中选择 JSON 的正则表达式

<script type="application\/ld\+json">(.*)<\/script>

在 Java 代码中:

String str = "<htm><section class=\"posts\"><script type=\"application/ld+json\">{\"url\": \"http://schema.org\",          \"title\": \"some Title\"}</script><article class=\"post\"></html>";
String regex = "<script type=\"application\\/ld\\+json\">(.*)<\\/script>";
Pattern pattern = Pattern.compile(regex, Pattern.DOTALL);
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
  System.out.println(matcher.group(1));
}

打印

{"url": "http://schema.org", "title": "some Title"}

参见 DEMO解释

关于java - 在 HTML 标签之间提取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31301776/

相关文章:

javascript - 按以逗号分隔的关键字突出显示文本

c++ - 使用 Qt 的正则表达式捕获一些文本

适用于所有语言的特殊字符的 Java 正则表达式

java - 锁可中断与锁

javascript - Android 应用程序 Phonegap 上的 CSS 无法正常工作

java - 如何在 Weblogic MbeanMaker MJF JAR 中包含外部依赖项?

html - Swift Vapor Leaf 在变量中传递 html

Javascript/jQuery - 使用正则表达式解析字符串中的主题标签,URL 中的 anchor 除外

Java错误: constructor cannot be applied to given types?

c# - 在 C# 中是否有相当于 Java 的标记中断或解决方法