【问题标题】:How to remove > tag from string in java如何从java中的字符串中删除>标签
【发布时间】:2019-03-21 07:37:55
【问题描述】:

我有以下字符串。 "Christmas is a very expensive> time of year for most> people so the <br/>Christmas> bazaar is an <b>opportunity</b> for parents to indulge their offspring and buy lots> of small items> as either presents or <b>stocking fillers</b> .|Trust me, it's not easy scooping up gift votives and <b>stocking stuffers</b>"

现在我只想从以单词结尾的字符串中删除">",而不是像"<br/> or <b"这样的html标签

如果我使用String.replace("\\>",""),那么它会从字符串中删除所有> 标签。
如何做到这一点?

【问题讨论】:

标签: java regex


【解决方案1】:

您可以使用 String.replace("string>", "string") 来实现结果。如果这不能解决您的问题,请提供更多详细信息。

【讨论】:

  • 我们不要急于给出解决方案,甚至连问题的全貌都没有。
  • 好的,感谢您的意见:)
【解决方案2】:

检查以下代码是否适合您的需要:

    String[] split = "This is test string> <br></br>".split(">");

    StringBuilder sb = new StringBuilder();
    for (String it : split) {
        if(it.contains("<")) {
            it += ">";
        }

        sb.append(it);
    }

    String result = sb.toString();

【讨论】:

    【解决方案3】:

    如果只需要删除第一次出现的"&gt;",请使用replacefirst(regex,"new-value");

    System.out.println("This istest string> <br></br>".replaceFirst(">",""));
    

    输出:

    This istest string <br></br>
    

    编辑:根据您的评论,“但我需要替换所有以字符串中的单词结尾的“>”。

    使用“positive lookbehind

    (?&lt;=String)&gt; (positive lookbehind) 匹配 string&gt; 中的 > (并且只有 >),但不匹配 somethingelse>。

    System.out.println("This istest string> <br></br>".replaceFirst("(?<=string)>",""));
    

    【讨论】:

    • 谢谢,我知道,但我需要替换所有以字符串中的单词结尾的“>”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 2015-03-24
    • 2014-01-07
    • 1970-01-01
    相关资源
    最近更新 更多