我正在尝试替换文档的 anchor 标记封闭 URL 中的所有非 anchor 标记封闭 URL。所以给定字符串:
I have two urls for google: <a href="http://www.google.com/">google</a> and http://www.google.com/
我想用这个替换它:
I have two urls for google: <a href="http://www.google.com/">google</a> and <a href="http://www.google.com/">http://www.google.com/</a>
有人知道在 Java 中执行此操作的干净方法吗?
最佳答案
这可能会帮助您入门(它适用于给定的示例):
public class test {
public static void main(String[] args) {
final String test = "I have two urls for google: <a href=\"http://www.google.com/\">google</a> and http://www.google.com/";
System.out.println(test.replaceAll("(?<!\\<a\\ href=\")http:\\/\\/[^ ]*",
"<a href=\"$0\"/>"));
}
}
它有一些问题:
- 它不考虑“a”标签中的空格,除了开头“a”和“href”之间的单个空格
- 假设 URL 为“http://”,后跟零个或多个不等于空格 ("") 的字符
这适用于简单的示例,我不确定您如何编写完整的解决方案。
关于Java : replacing all URLs with anchor tags that aren't already in anchor tags,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3144208/