Removing url from text using ruby

Given the text, I want to remove part of the url and leave another text.

Example:

'bla bla bla... bla bla bla... http://bit.ly/someuri bla bla bla...'

to become

'bla bla bla... bla bla bla... bla bla bla...'

Is there any ruby ​​method in a method to do this efficiently?

+5
source share
2 answers

Try with regex:

(?:f|ht)tps?:\/[^\s]+
+9
source

I just found a Regular Expression - replace the word except the URL / URI and change the code this way:

URI_REGEX = %r"((?:(?:[^ :/?#]+):)(?://(?:[^ /?#]*))(?:[^ ?#]*)(?:\?(?:[^ #]*))?(?:#(?:[^ ]*))?)"

def remove_uris(text)
  text.split(URI_REGEX).collect do |s|
    unless s =~ URI_REGEX
      s
    end
  end.join
end

I am testing it in the rails console and it works as expected:

remove_uris('bla bla bla... bla bla bla... http://bit.ly/someuri bla bla bla...')
=> "bla bla bla... bla bla bla...  bla bla bla..."

If someone has a better / effective solution, I will vote or accept it. Thank.

+4
source

All Articles