5

Given a text, I want to remove the url part and leave other 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 build in method to do this efficiently?

2
  • Can you guarantee there won't be any spaces within the url? Commented Jun 16, 2011 at 7:52
  • The text is entered by user, so my main concern is just remove anything that resembles a url up to the next space. 'http://bit.ly/the url with space' will become 'url with space' Commented Jun 16, 2011 at 8:06

2 Answers 2

9

Try with regex:

(?:f|ht)tps?:\/[^\s]+
Sign up to request clarification or add additional context in comments.

2 Comments

@Donny Kurnia lets say you have your string in a variable str, then you can use @The Mask's regex like so : new_str = str.gsub(/(?:f|ht)tps?:\/[^\s]+/, '') or if you want str itself to change you can do str.gsub!(/(?:f|ht)tps?:\/[^\s]+/, '')
@DhruvaSagar the answer above worked where mine failed. @inbound_text.gsub!(/<http:(.*)>/m, ''). Why? Nice answer.
4

I just found Regular Expression - replace word except within a URL/URI and modify the code to be like this:

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

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

I test it in rails console and it worked 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 anyone have better / effective solution, I will vote up or accept it. Thanks.

2 Comments

what about text.gsub!(URI_REGEX, '') ?
Please note that this doesn't work 100%. Consider the following text: "تفاصيل تغطية\n#lexusriyadhlargestglobally\n#لكزس_الرياض_الأكبر_في_العالم\nتجدونها هنا👇\nhttp://example.com\n👏👌👍 http://example.com" some parts of the arabic text and emojis are left out

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.