2016-05-16 123 views
1

所以我有這個簡單的文字:獲得從文本鏈接

To activate your account click the link below: 
https://tbeyfee-gkg9834636j-gergity3yu3hgge-drgengo9476y3ltjne 
If the above URL does not work try copying and pasting it into your browser. If you continue to have problem please feel free to contact us. 
If you have any questions, please do not hesitate to contact your account manager directly or email us at [email protected] and we'll get right back to you. 
Thanks again for choosing logger. 
Kind regards, 
The Logger Team 

會是什麼簡單的方法來抓住這個https鏈接?

這是我嘗試:

val str = "" // This is my string. 
val pattern = new Regex("^https.*$") 

println(pattern.findAllIn(str)) 
+0

這是1:'^ https。* $'' – ritesht93

+0

你是否堅持使用Scala代碼或正則表達式?有關正則表達式,請參閱http://stackoverflow.com/questions/3809401/what-is-a-good-regular-expression-to-match-a-url。 –

+0

請參閱我的更新。 –

回答

2

可以使用多修飾符(?m)與您正則表達式,這將使^$一個的開始和結束匹配整個字符串,而不是

var str = "To activate your account click the link below:\nhttps://tbeyfee-gkg9834636j-gergity3yu3hgge-drgengo9476y3ltjne\nIf the above URL does not work try copying and pasting it into your browser. If you continue to have problem please feel free to contact us.\nIf you have any questions, please do not hesitate to contact your account manager directly or email us at [email protected] and we'll get right back to you.\nThanks again for choosing logger.\nKind regards,\nThe Logger Team" 
val pattern = new Regex("(?m)^https://.+$") 
val res = pattern.findFirstIn(str) 
println(res) 

Ideone demo

我也建議用+替換*(0或多次出現)量詞匹配1個或多個的任何字符,但換行符(與.)。此外,您可以使用https?://\S+來匹配較大文本內的大部分網址。

由於您只需要1個網址,我建議您使用findFirstIn而不是findAllIn(請參閱Scala Regex reference)。