0

Suppose I only want user to type in url starts with http://www.google.com What is the regular expression for this?

Thanks!

4 Answers 4

2

Just get the substring from 0 to the length of http://www.google.com and you're done.

Sign up to request clarification or add additional context in comments.

Comments

1

Rather than use a regex, you might want to consider using the URI library that comes with Ruby. It's made to take apart and build URLs, is well tested, and less error-prone than trying to reinvent the same functionality.

require 'uri'

url = URI.parse('http://www.google.com/path/to/page.html?a=1&b=2')
url.scheme # => "http"
url.host   # => "www.google.com"
url.path   # => "/path/to/page.html"
url.query  # => "a=1&b=2"

If that's not good enough, the Addressable::URI gem is even more capable.

Comments

0

Try this:

/\Ahttp:\/\/www\.google\.com(.*)?\Z/

ruby-1.9.2-p0 > "http://www.google.com" =~ /\Ahttp:\/\/www\.google\.com(.*)?\Z/
=> 0 
ruby-1.9.2-p0 > "http://www.google.com/foobar" =~ /\Ahttp:\/\/www\.google\.com(.*)?\Z/
=> 0 
ruby-1.9.2-p0 > $1
=> "/foobar" 

Comments

0

Rails has a convenient start_with? method for this. If it's just a static string, no regular expression is needed.

url.start_with?("http://www.google.com")

Comments

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.