簡體   English   中英

標簽中的Java替換鏈接

[英]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> ?:

只需使用類似於此答案的方法替換urltext

如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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM