【问题标题】:Regular expression to remove Some HTML tags but keep Span tag正则表达式删除一些 HTML 标签但保留 Span 标签
【发布时间】:2013-10-30 13:10:19
【问题描述】:

是否有一个表达式可以获取两个 HTML 标签之间的值?此外,如果 Span 标签存在,那么我需要保持原样

input
<table><tr>
<td>abc<td/> <span class="abc">Test</span>
</tr>
</table>

Output

abc <span class"abc"> Test</span>

我尝试了以下解决方案,但它也删除了标签

String input="<table><tr><td>abc<td/> <span>Test</span></tr></table>";
        String newValue = input.replaceAll("<[^>]*>", "");
        System.out.println(newValue);

以上代码的输出

abc Test

但输出需要

abc <span class"abc"> Test</span>

【问题讨论】:

  • 你有代码吗?
  • 我尝试删除 Html 标签,例如-- input.replaceAll("]*>", "");但我需要保持 标签原样。以上代码删除所有html代码
  • @Raje 看,你需要在你的问题中提供。否则我们会认为你没有尝试过任何东西:)
  • 哦..我会更新我的问题。谢谢建议
  • @chrylis 是正确的。 不可能使用正则表达式可靠地解析任何类似 xml 的语言,因为这些语言允许递归语法。见codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html

标签: java html regex


【解决方案1】:

您可以使用否定的前瞻(?!...),这意味着后面没有来测试标签。 java语法示例:

<(?!/?span\\b)[^>]*>

【讨论】:

    【解决方案2】:

    我认为这会满足您的要求:

    str.replaceAll("<(?!\\/?span)[^>]+>", "")
    

    这将查找&lt;,然后在查找下一个&gt;之前查看它是否包含/spanspan...并将所有内容替换为空。

    Example:

    String str = "<table><tr><td>abc<td/> <span class=\"abc\">Test</span></tr></table>\";";
    System.out.println(str.replaceAll("<(?!\\/?span)[^>]+>", ""));
    //prints: abc <span class="abc">Test</span>";
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-05-15
      • 2011-04-16
      • 1970-01-01
      • 1970-01-01
      • 2019-11-25
      相关资源
      最近更新 更多