我有一个难题需要您的帮助:我需要用 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>
问题:另一个链接中有一个链接。
你知道如何解决这个问题吗?
提前谢谢
最佳答案
使用正则表达式解析 HTML 总是一个坏主意,正是因为像这样的奇怪情况。最好使用 HTML 解析器。 Java 有一个内置的 HTML 解析器 using Swing您可能想研究一下。
关于java - REGEX:在 HTML 文本中添加链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6441120/