2014-12-03 42 views
1

複雜的URL我一直在尋找在文本檢測URL,這樣我可以用超鏈接替換它們正則表達式。我達到同樣的正常網址像www.facebook.comhttps://google.com但其在某些情況下像https://xyzSite.com/getUser.action?id=123&pwd=5失敗。你如何建議我可以檢測具有上述參數的網址。我目前使用下面的正則表達式檢測在GWT

(((ftp|http|https)://)?[\\[email protected]\\-\\_]+\\.[a-zA-Z]{2,}(:\\d{1,5})?(/[\\w#!:.?+=&%@!\\_\\-/]+)*)

+1

你可能想嘗試包裹https://github.com/twitter/twit ter-text-js而不是寫你自己的(或者可能將它移植到GWT;這裏還有https://github.com/twitter/twitter-text-java但它使用了一些GWT不兼容班) – 2014-12-03 11:07:08

+0

我會寫使用庫這一點。與生產模式相比,GWT在單元測試中使用稍微不同的正則表達式語法。 如果你想在自己寫的模式,你應該使用GWTTestCase,而不是Junit的。 – 2014-12-03 11:20:12

+0

@Christian:是的,你可能寫了,但我們有種使用我們自己的內部工具進行單元測試,所以單元測試不是問題。我現在使用replaceAll本身生成超鏈接文本,如下所示,它現在對我很好: 'public static String insertAnchorsForURLs(String ans){ \t \t返回ans.replaceAll(「((https? | FTP |文件):??!//)。\\ W @ \\ - \\ _] + \\ [-a-ZA-Z0-9 + @#/%=〜_ |:, 。;] * [ - α-ZA-Z0-9 + @#/%=〜_ |] 「」 $0「); \t}' – Sourabh 2014-12-04 05:27:20

回答

0

我發現下面的函數解決我的問題:

public static String insertAnchorsForURLs(String ans) { 
     return ans.replaceAll("((https?|ftp|file)://)?[\\[email protected]\\-\\_]+\\.[-a-zA-Z0-9+&@#/%?=~_|!:,.;]*[-a-zA-Z0-9+&@#/%=~_|]", "<a target='_blank' href = \'$0\'>$0</a>"); 
    } 

我已經測試了以下的情況下在此:

www.google.com 
www.somesite.org.in 
www.mysite.com/whatever.action 
www.mysite.com/whatever.action?id=1&pwd=2 
https://google.com 
http://google.co.in