我想所有的鏈接轉換給定的字符串使用下面的代碼可點擊a
標籤:斯普利特空間,但不換行
String [] parts = comment.split("\\s");
String newComment=null;
for(String item : parts) try {
URL url = new URL(item);
// If possible then replace with anchor...
if(newComment==null){
newComment="<a href=\"" + url + "\">"+ url + "</a> ";
}else{
newComment=newComment+"<a href=\"" + url + "\">"+ url + "</a> ";
}
} catch (MalformedURLException e) {
// If there was an URL that was not it!...
if(newComment==null){
newComment = item+" ";
}else{
newComment = newComment+item+" ";
}
}
它工作正常的
Hi there, click here http://www.google.com ok?
將其轉換爲
Hi there, click here <a href="http://www.google.com">http://www.google.com</a> ok?
但當字符串是這樣的:
Hi there, click
here http://www.google.com
ok?
它還是將其轉換爲:
Hi there, click here <a href="http://www.google.com">http://www.google.com</a> ok?
而我想最後的結果是:
Hi there, click
here <a href="http://www.google.com">http://www.google.com</a>
ok?
我認爲它包括換行符也同時使分裂。
如何在這種情況下保留換行符?
\ s不僅僅匹配空格,它匹配任何空白字符,包括新行(請參閱http://stackoverflow.com/questions/225337/how-do-i-split-a-string-with-any -whitespace-chars-as-delimiters) - 爲什麼不把空格字符放在裏面? – eldris
哦謝謝!我不知道:) – soundswaste