这是我的正则表达式:
s = /(?<head>http|https):\/\/(?<host>[^\/]+)/.match("http://www.myhost.com")
如何获取head
和host
群组?
答案 0 :(得分:5)
s['head'] => "http"
s['host'] => "www.myhost.com"
您也可以使用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"
答案 1 :(得分:2)
使用captures
&gt;&gt;
string = ...
one, two, three = string.match(/pattern/).captures
答案 2 :(得分:0)
您应该如上所述将uri库用于此目的,但每当您将字符串与正则表达式匹配时,您可以使用特殊变量获取捕获的值:
“foo bar baz”=〜/(bar)\ s(baz)/
$ 1
=&GT; '酒吧'
$ 2
=&GT; '巴兹'
依旧......