1

Here is my regex:

s = /(?<head>http|https):\/\/(?<host>[^\/]+)/.match("http://www.myhost.com")

How do I get the head and host groups?

1
  • Why don't you reuse an invented wheel, like Ruby's built-in URI or Addressable::URI? Commented Nov 28, 2012 at 1:40

3 Answers 3

5
s['head'] => "http"
s['host'] => "www.myhost.com" 

You could also use URI...

1.9.3p327 > require 'uri'
 => true 
1.9.3p327 > u = URI.parse("http://www.myhost.com")
 => #<URI::HTTP:0x007f8bca2239b0 URL:http://www.myhost.com> 
1.9.3p327 > u.scheme
 => "http" 
1.9.3p327 > u.host
 => "www.myhost.com" 
Sign up to request clarification or add additional context in comments.

Comments

2

Use captures >>

string = ...
one, two, three = string.match(/pattern/).captures

2 Comments

How do you do this in context, ie, with his regex?
@JustJake - With your "current" regex pattern (with some minor optimization) it would be head, host = "http://www.myhost.com".match(/(https?):\/\/([^\/]+)/).captures. As you can see, the regex pattern has two groups (...), and their matches will be assigned into head, host.
0

You should probably use the uri library for this purpose as suggested above, but whenever you match a string to a regex, you can grab captured values using the special variable:

"foo bar baz" =~ /(bar)\s(baz)/

$1

=> 'bar'

$2

=> 'baz'

and so on...

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.