david hol
david hol

Reputation: 1280

Get link from text

So i have this simple text:

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

What would be the simple way to catch this https link ?

This is what i have try:

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

println(pattern.findAllIn(str))

Upvotes: 1

Views: 65

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626926

You can use the multiline modifier (?m) with your regex that will make ^ and $ match the start and end of a line instead of a whole string:

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)

See Ideone demo

I also suggest replacing * (0 or more occurrences) quantifier with + to match 1 or more occurrences of any character but a newline (with .). Also, you may use https?://\S+ to match most of the URLs inside larger texts.

Since you only need 1 URL, I suggest using findFirstIn instead of the findAllIn (see Scala Regex reference).

Upvotes: 2

Related Questions