使用RegExp和Java删除一些HTML标记

使用RegExp和Java删除一些HTML标记,java,html,regex,Java,Html,Regex,我想从字符串中删除HTML标记。 这很容易,我知道,我做到了: public String removerTags(String html) { return html.replaceAll("\\<(/?[^\\>]+)\\>", " ").replaceAll("\\s+", " ").trim(); } 公共字符串移除标记(字符串html) { 返回html.replaceAll(“\\]+)\\>”,“”)。repl

我想从字符串中删除HTML标记。 这很容易,我知道,我做到了:

public String removerTags(String html)  
    {  
        return html.replaceAll("\\<(/?[^\\>]+)\\>", " ").replaceAll("\\s+", " ").trim();  
    }  
公共字符串移除标记(字符串html)
{  
返回html.replaceAll(“\\]+)\\>”,“”)。replaceAll(“\\s+”,“”)。trim();
}  
问题是我不想删除所有标签。。我想要标签

<span style=\"background-color: yellow\"> (text) </ span>
(文本)
在绳子上保持完整

我正在使用它作为使用GWT搜索web应用程序时的一种“亮点”

我需要这样做,因为如果搜索发现包含一些HTML标记的文本(索引由Lucene完成),并且该文本被破坏,来自SafeThmlBuilder的appendHTML将无法装入字符串

你能以一种相当好的方式做到这一点吗


拥抱。

我强烈建议您使用。正则表达式根本不适合这个任务。对于JSoup来说,它基本上是一个简单、可读且易于维护的单行程序

看看这个方法,也许还有这篇文章:


    • 我过去使用过的一个非常有效的库是


      这绝对允许标记的白名单/黑名单。可能值得一看。

      我只使用正则表达式找到了这个问题的解决方案:

      publicstaticstringfilterthmltags(stringhtml){
      //保存有效标记:
      String striped=html.replaceAll(“(?i)\\”,“{{$1}”);
      //删除所有标记:
      striped=striped.replaceAll(“\\]+)\\>”,“”);
      //还原有效标记:
      striped=striped.replaceAll(“\\{\\{(.+?)\\}\\\},”);
      返回条纹;
      }
      
      确保在html内容中不使用“{…}”。您可以轻松更改此“保存顺序”。有效标记在first replaceAll正则表达式列表中定义:

      (a | h\d | b | i | em | cite | code | strong | pre | br)

      上面列表中的“h\d”表示“h1,h2,…”是有效的标记

      我用以下代码测试了这一点:

      public static void main (String[] args) {
      
          String teste = " <b>test bold chars</b> <BR/> <div>test div</div> \n" +
                  " link: <a href=\"test.html\">click here</a> <br />\n" +
                  " <script>bad script</script> <notpermitted/>\n";
      
          System.out.println("teste: \n"+teste);
          System.out.println("\n\n\nstriped: \n"+filterHTMLTags(teste));
      }
      
      publicstaticvoidmain(字符串[]args){
      String teste=“test bold chars
      test div\n”+ “链接:
      \n”+ “错误的脚本\n”; System.out.println(“teste:\n”+teste); System.out.println(“\n\n\n说明:\n”+filtertmltags(teste)); }
      再见, 塞尔吉奥·菲盖雷多-

      这些问题现在很常见。为什么我们不能把类似的问题集中在一起#所以提示;)请确保您也考虑到实体引用值。这将删除所有我的HTML标记。哦,不。。。你可以为这个方法提供一个你不想让它干扰的标签白名单。我只是“解决”了我的问题,我在突出显示之前删除了标签。。。因此,在此之后,只会显示正确的标记!谢谢,伙计。谢谢,下次我需要做这种事情的时候,我会记住那个图书馆。