2013-10-14 49 views
0

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

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

你能证明我的这一目的的正则表达式:

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

将被替代?非常感谢。

+2

不要使用正则表达式,使用'HTML' [parser](http://stackoverflow.com/questions/2168610/which-html-parser-is-best)。 – Maroun

+0

它是您想要替换的特定链接和文本,还是您想要将所有链接和所有文本替换为“http:// anotherweb.com”和“锚文本2”? – Jerry

+0

我想要替换文本中的所有链接和所有文本。 –

回答

1

也许你可以使用一个replaceAll与正则表达式:

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

并将其替换:

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

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

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); 
+0

我会尽力的。谢谢 –