Home > OS >  How to extract a url from a string with spaces and punctuation marks?
How to extract a url from a string with spaces and punctuation marks?

Time:11-04

Let's say you have a string like this: "This is my.linkhttps://google.com/1two3!!!"

And you want to get exactly: https://google.com/1two3

Tried:

message.split.select{ |m| m.include?("google") }

but it does not split periods. so ti includes my.link and !!!.

message.split(/[\s.] /)

but it splits the link itself.

CodePudding user response:

I would use a regex that accommodates any url:

"This is my.linkhttps://google.com/1two3!!!".match(/https:[\/\w\.]*/)[0]
#=> "https://google.com/1two3"
  • Related