使用正则表达式替换链接标记

时间:2013-10-14 07:56:34

标签: java regex

我正在使用java。我想找到然后替换标签<a> html的超链接和锚文本。我知道我必须使用replace()方法,但我对正则表达式非常不满意。 一个例子:

<a href="http://example.com">anchor text 1</a>

将替换为:

<a href="http://anotherweb.com">anchor text 2</a>

你能为此目的展示我的正则表达式吗?非常感谢。

2 个答案:

答案 0 :(得分:2)

请勿使用正则表达式执行此任务。您应该使用一些HTML解析器,如Jsoup

String str = "<a href='http://example.com'>anchor text 1</a>";

Document doc = Jsoup.parse(str);
str = doc.select("a[href]").attr("href", "http://anotherweb.com").first().toString();

System.out.println(str);

答案 1 :(得分:1)

您可以使用正则表达式replaceAll

<a href=\"[^\"]+\">[^<]+</a>

并替换为:

<a href=\"http://anotherweb.com\">anchor text 2</a>

[^\"]+[^<]+被否定了,并且将分别匹配除"<之外的所有字符。

相关问题