Java:用锚标记替换所有URL,锚标记不在锚标记中

时间:2010-06-29 19:52:19

标签: java regex url replace

我正在尝试替换文档中包含锚标记的URL中所有非锚标记的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做一个干净的方法?

1 个答案:

答案 0 :(得分:1)

这可能会让你开始(它适用于给定的例子):

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”之间的单个空格
  • 假设网址为“http://”,后跟零个或多个不等于空格的字符(“”)

这适用于简单的示例,我不确定您是如何编写完整的解决方案。