【问题标题】:REGEX: adding links in an HTML text正则表达式:在 HTML 文本中添加链接
【发布时间】:2011-09-20 10:22:00
【问题描述】:

我有一个难题需要您的帮助:我需要用 HTML 文本中的链接替换某些单词。

For example, I have to replace "word" with "<a href="...">word</ a>"

难度加倍:

  • 1。不要在标签属性中添加链接
  • 2。不要添加链接其他链接(嵌套链接)。

我找到了满足情况(1)的解决方案,但我无法处理情况(2)。

这是我的简化代码:

String text="sample text <a>sample text</a> sample <a href='http://www.sample.com'>a good sample</a>";
String wordToReplace="sample";
String pattern="\\b"+wordToReplace+"\\b(?![^<>]*+>)"; //the last part is here to solve de problem (1)
String link="["+wordToReplace+"]"; //for more clarity, the generated link is replaced by [...]

System.out.println(text.replaceAll(pattern,link));

结果是:

[sample] text <a>[sample] text</a> [sample] <a href='http://www.sample.com'>a good [sample]</a>

问题:另一个链接中有一个链接。

你知道如何解决这个问题吗?

提前谢谢你

【问题讨论】:

标签: java html regex hyperlink add


【解决方案1】:

使用正则表达式解析 HTML 总是一个坏主意,正是因为这种奇怪的情况。最好使用 HTML 解析器。 Java 有一个内置的带有using Swing 的 HTML 解析器,您可能想研究一下。

【讨论】:

    猜你喜欢
    • 2010-09-30
    • 2011-04-28
    • 2018-08-02
    • 1970-01-01
    • 1970-01-01
    • 2012-12-01
    • 1970-01-01
    • 2014-10-24
    • 1970-01-01
    相关资源
    最近更新 更多