【问题标题】:Extract tags between tags Java Regex [closed]提取标签之间的标签Java Regex [关闭]
【发布时间】:2013-07-20 16:30:43
【问题描述】:

我想提取<body></body>之间的标签

String patternHtml = "(*?)<body>(.*?)</body>(*?)";
Pattern rHtml = Pattern.compile(pattern, Pattern.DOTALL | Pattern.CASE_INSENSITIVE);
Matcher mHtml = rHtml.matcher(html);

我不知道为什么,但这会提取所有带有 &lt;head&gt;&lt;style&gt; 的标签...

请:我需要使用正则表达式,请不要提供解析器库之类的替代方案...

【问题讨论】:

  • 您是否尝试过从正则表达式的开头和结尾删除(*?)?也不要忘记在匹配器对象上使用 find() 方法。顺便说一句,我希望您不会在某些实际应用中使用此代码,而只是学习正则表达式。
  • 您是否意识到您的问题与“我不知道为什么但是螺丝刀没有击中钉子......请:我需要使用螺丝刀,请不要不提供像锤子这样的替代品......”?答案非常简单:为工作使用正确的工具!
  • @BalusC 我知道使用解析器库会更好。但是,如果您看到我的帖子,这不是我的问题..
  • @Orçunyumarcı “但这不是我的问题”——不要说得太细,这个问题很愚蠢。它基本上是这样写的:“我不愿意接受帮助。”这不是一个问题,这是一个声明——我们不喜欢它。
  • 这个问题似乎是题外话,因为它是关于 OP 已经明确表示他们对帮助不感兴趣。

标签: java regex html-parsing


【解决方案1】:

如果您只想(我引用)“提取标签”,我将其解释为打开节点,在您的 html 文本的正文语句中,您可以使用下面的解决方案。

请注意,这是野蛮。您不应该使用正则表达式“解析”html(我知道 知道,但其他读者可能不知道)。

// simple html file, has head/body and line breaks
String html = "<html>\r\n<head>\r\n<title>Foo</title>\r\n</head>\r\n" +
        "<body>\r\n<h1>Blah</h1>\r\n<h3>Meh</h3>\r\n</body>\r\n</html>";
// the pattern only checks for opening nodes
Pattern tagsWithinBody = Pattern.compile("<\\p{Alnum}+>");
// matcher is applied to whatever text is in between the "<body>" open and close nodes
Matcher matcher = tagsWithinBody.matcher(html.substring(html.indexOf("<body>") + 1, html.indexOf("</body>")));
// iterates over matcher as long as it finds text
while (matcher.find()) {
    System.out.println(matcher.group());
}

输出:

<h1>
<h3>

【讨论】:

    猜你喜欢
    • 2012-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多