[英]Java replace link in a tag
我有
String s = "<a href="https://stackoverflow.com">https://stackoverflow.com</a><br/><a href="https://google.com">https://google.com</a>"
現在,我只想用固定值(例如`abc.com?)作為前綴替換href
屬性中的所有鏈接。 這是我想要的結果:
String s = "<a href="abc.com?url=https://stackoverflow.com">https://stackoverflow.com</a><br/><a href="abc.com?url=https://google.com">https://google.com</a>"
我嘗試了以下操作,但不能解決問題,因為它替換了以 http://
開頭的所有字符串,而不僅替換了 href
屬性中的那些字符串:
s= s.replaceAll("http://.+?(com|net|org|vn)/{0,1}","abc.com" + "&url=" + "$0");
我該怎么做才能僅在屬性中而不是其他內容中進行替換?
您可以使用HTML解析器,例如JSoup
String s = "<a href="https://stackoverflow.com">https://stackoverflow.com</a>";
Document document = JSoup.parse(s);
Elements anchors = document.getElementsByTag("a");
anchors.get(0).attr("href", "...new href...");
或者,如果這太重了,那么正則表達式就足夠了:
<a href="(?<url>[^"]+)">(?<text>[^<]+)<\/a>
請注意,如果您不關心text
組,請用?<text>
替換?<text>
?:
只需使用類似於此答案的方法替換url
和text
組
如RealSkeptic所說,查找href而不是鏈接本身,可以節省很多工作。
var s = '<a href="http://stackoverflow.com">https://stackoverflow.com</a><br/><a href="https://google.com">https://google.com</a>'; s = s.replace(/href="/g,"href=\\"abc.com&url=" ); console.log(s);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.