Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove "http://" and "https://" from a string

Tags:

regex

ruby

am new to ruby using regular expression .how can i remove https and http and www from a string

server= http://france24.miles.com
server= https://seloger.com

from these sites i want to remove all http ,https and www

france24.miles.com
seloger.com

i used following code but it is not woking for me

server = server.(/^https?\:\/\/(www.)?/,'')
like image 379
Psl Avatar asked Jun 24 '14 04:06

Psl


People also ask

How do I remove a link from text in Python?

sub(r'http\S+', '', my_string) . The re. sub() method will remove any URLs from the string by replacing them with empty strings.


Video Answer


2 Answers

server = server.(/^https?\:\/\/(www.)?/,'')

This didn't work, because you aren't calling a method of the string server. Make sure you call the sub method:

server = server.sub(/^https?\:\/\/(www.)?/,'')

Example

> server = "http://www.stackoverflow.com"
> server = server.sub(/^https?\:\/\/(www.)?/,'')
stackoverflow.com

As per the requirement if you want it to work with the illegal format http:\\ as well, use the following regex:

server.sub(/https?\:(\\\\|\/\/)(www.)?/,'')
like image 166
14 revs, 12 users 16% Avatar answered Oct 18 '22 15:10

14 revs, 12 users 16%


Std-lib URI is dedicated for such kind of work. Using this would be simpler and may be more reliable

require 'uri'

uri = URI.parse("http://www.ruby-lang.org/")

uri.host
=> "www.ruby-lang.org"

uri.host.sub(/\Awww\./, '')
=> "ruby-lang.org"
like image 24
Billy Chan Avatar answered Oct 18 '22 13:10

Billy Chan