0

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

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

将被替换为:

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

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

4

2 回答 2

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);
于 2013-10-14T08:02:10.760 回答
1

您也许可以将 areplaceAll与正则表达式一起使用:

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

并替换为:

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

[^\"]+[^<]+是否定类,将匹配除"和之外的所有字符<

于 2013-10-14T08:38:33.300 回答