【问题标题】:Removing a substring between two characters (java)删除两个字符之间的子字符串(java)
【发布时间】:2012-05-14 18:54:34
【问题描述】:

我有一个类似这样的 java 字符串:

String string = "I <strong>really</strong> want to get rid of the strong-tags!";

我想删除标签。我还有一些其他的字符串,其中的标签更长,所以我想找到一种方法来删除“”字符之间的所有内容,包括那些字符。

一种方法是使用将字符串与正则表达式进行比较的内置字符串方法,但我不知道如何编写。

【问题讨论】:

    标签: java regex string substring


    【解决方案1】:

    在使用正则表达式解析 HTML 时建议小心(由于其允许的复杂性),但是对于“简单”HTML 和简单文本(其中没有文字 &lt;&gt; 的文本),这将起作用:

    String stripped = html.replaceAll("<.*?>", "");
    

    【讨论】:

      【解决方案2】:

      为了避免正则表达式:

      String toRemove = StringUtils.substringBetween(string, "<", ">");
      String result = StringUtils.remove(string, "<" + toRemove + ">"); 
      

      对于多个实例:

      String[] allToRemove = StringUtils.substringsBetween(string, "<", ">");
      String result = string;
      for (String toRemove : allToRemove) {
        result = StringUtils.remove(result, "<" + toRemove + ">"); 
      }
      

      Apache StringUtils 函数为 null、空且不匹配

      【讨论】:

        【解决方案3】:

        你应该使用

        String stripped = html.replaceAll("<[^>]*>", "");
        String stripped = html.replaceAll("<[^<>]*>", "");
        

        其中&lt;[^&gt;]*&gt; 匹配以&lt; 开头的子字符串,然后匹配除&gt; 之外的零个或多个字符(如果您选择第二个版本,则匹配除&lt;&gt; 之外的字符),然后是@987654330 @字符。

        注意&lt;.*?&gt;

        请参阅regex demo

        【讨论】:

          猜你喜欢
          • 2018-11-25
          • 2016-07-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2010-12-25
          • 2019-12-30
          • 2019-04-02
          相关资源
          最近更新 更多