icn
icn

Reputation: 17876

ruby regex: how to get group value

Here is my regex:

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

How do I get the head and host groups?

Upvotes: 1

Views: 569

Answers (3)

James Martin
James Martin

Reputation: 96

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...

Upvotes: 0

user1858213
user1858213

Reputation:

Use captures >>

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

Upvotes: 2

Philip Hallstrom
Philip Hallstrom

Reputation: 19879

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" 

Upvotes: 5

Related Questions