如何从Java中的字符串中删除>标签

时间:2018-10-16 17:36:05

标签: java regex

我有以下字符串。 "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("\\>",""),那么它将删除字符串中的所有>标记。
如何实现?

4 个答案:

答案 0 :(得分:2)

我已经完成了一个灵活高效的HTML解析器,可以在此处下载:

  

http://developer.torello.directory/JavaHTML/index.html

这是您的问题已解决:

import Torello.HTML.*;
import Torello.Java.*;
import java.util.*;
import java.io.*;

public class ReplaceGreaterThan
{
    public static void main(String[] argv) throws IOException
    {
        String YOUR_STRING_VAR = "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>";
        Vector<HTMLNode> page = HTMLPage.getPageTokens(YOUR_STRING_VAR, false);
        HTMLNode n;
        for (int i=0; i < page.size(); i++)
            if ((n = page.elementAt(i)) instanceof TextNode)
                if (n.str.contains("<") || n.str.contains(">"))
                    page.setElementAt(new TextNode(n.str.replaceAll("(<|>)", "")), i);
        YOUR_STRING_VAR = HTMLNodeFunction.pageToString(page);
        System.out.println(YOUR_STRING_VAR);
    }
}

以下是输出:

  

对于大多数人来说,圣诞节是一年中非常昂贵的时间,因此圣诞节集市是父母沉迷的机会   他们的后代并购买很多小东西作为礼物或   填充填充物。|相信我,这不容易获得礼物   奉献者和放养毛绒玩具

答案 1 :(得分:1)

检查以下代码是否满足您的需求:

    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();

答案 2 :(得分:0)

您可以使用String.replace(“ string>”,“ string”)获得结果。如果这样做不能解决您的问题,请提供更多详细信息。

答案 3 :(得分:0)

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

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

输出:

This istest string <br></br>

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

使用“ positive lookbehind

(?<=String)>(正向后)与string>中的>(且仅>)匹配,但不匹配其他东西。

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