【问题标题】:Remove all HTML tags except <br> from a text?从文本中删除除 <br> 之外的所有 HTML 标记?
【发布时间】:2011-02-14 09:05:05
【问题描述】:

大家好 我有一个我想要的 java 字符串 1-从中删除除新行标签&lt;br&gt;&lt;/br&gt;之外的所有html标签,如果有文本,则将文本保留在标签内。 2-解析后的文本结果相互连接,如: text1andtext2 ,文本之间没有空格分隔,我也想这样做。

这就是我正在做的事情:

String html = "<div dir=\"ltr\">hello my friend<span>ECHO</span><br>how are you ?<br><br><div class=\"gmail_quote\">On Mon, Feb 14, 2011 at 10:45 AM, My Friend <span dir=\"ltr\">&lt;<a href=\"mailto:notifications@mydomain.com\">notifications@mydomain.com</a>&gt;</span> wrote:<br> "
            + "<blockquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 0pt 0.8ex; border-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;\"> ";
    String parsedText = html.replaceAll("\\<.*?\\>", "");
    System.out.println(parsedText);

当前输出:

hello my friendECHOhow are you ?On Mon, Feb 14, 2011 at 10:45 AM, My Friend &lt;notifications@mydomain.com&gt; wrote:

想要的输出:

hello my friend ECHO <br> how are you ? <br> <br> On Mon, Feb 14, 2011 at 10:45 AM, My Friend &`lt;notifications@mydomain.com&gt; wrote:`

【问题讨论】:

  • 不,我不想删除所有 html 标签,因为这实际上是代码正在做的事情,我想删除除新行标签之外的所有 html 标签。

标签: java regex


【解决方案1】:

你可以这样做:

final String html =
    "<div dir=\"ltr\">hello my friend<span>ECHO</span><br>how are you ?" +
    "<br><br><div class=\"gmail_quote\">On Mon, Feb 14, 2011 at 10:45 AM," +
    " My Friend <span dir=\"ltr\">&lt;<a href=\"mailto:notifications@mydo" +
    "main.com\">notifications@mydomain.com</a>&gt;</span> wrote:<br><bloc" +
    "kquote class=\"gmail_quote\" style=\"margin: 0pt 0pt 0pt 0.8ex; bord" +
    "er-left: 1px solid rgb(204, 204, 204); padding-left: 1ex;\"> ";
final Pattern tagPattern = Pattern.compile("<([^\\s>/]+).*?>");
final Matcher matcher = tagPattern.matcher(html);
final StringBuffer sb = new StringBuffer(html.length());
while(matcher.find()){
    matcher
        .appendReplacement(sb, matcher.group(1).equalsIgnoreCase("br")
            ? matcher.group()
            : " ");
}
matcher.appendTail(sb);

final String parsedText = sb.toString();
System.out.println(parsedText);

输出:

hello my friendECHO<br>how are you ?<br><br>On Mon, Feb 14, 2011 at 10:45 AM,
My Friend &lt;notifications@mydomain.com&gt; wrote:<br>  

但我希望你知道Cthulhu is calling if you do。不要用 Regex 解析 HTML / XML!

【讨论】:

  • 非常感谢上面的例子,但你的意思是我应该用像 Jsoup 这样的 html 解析器来做吗?
  • 我的意思是,对于这样一个简单的例子,Regex 可能没问题,但如果它变得更复杂一点,是的,JSoup 可能是一个好主意。
  • @Sean:“但我希望你知道,如果你知道,克苏鲁在召唤你。”有趣的回复:)
  • 那么文本格式 hello myfriendECHO 之间应该有一个空格
  • @James 不是我自己的想法,不幸的是:codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html
【解决方案2】:

我愿意

  • 用换行符或其他特殊字符替换所有
  • 删除所有标签。
  • 将特殊字符替换为

【讨论】:

    【解决方案3】:
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多