如何使用正则表达式模式从 URL 中提取参数

How to extract a parameter from a URL using a regex pattern

我在匹配表达式时遇到问题。我想从使用 Nokogiri 提取的 link 中提取 "code" 参数,所以我尝试了:

event_id = a.attr("href").match(/\?code=(\d+)/)[1]

不幸的是,提取的是整个查询字符串:

?code=768140119

仅获取参数值而不获取其他任何内容的正确方法是什么?

不要使用正则表达式,使用经过良好测试的轮子。

Ruby的URI class is your friend, in particular decode_www_form:

require 'uri'

uri = URI.parse('http://foo.com?code=768140119')
uri.query # => "code=768140119"
URI.decode_www_form(uri.query) # => [["code", "768140119"]]
URI.decode_www_form(uri.query).to_h # => {"code"=>"768140119"}

至于提取标签参数的值,Nokogiri 很容易,只需将节点视为散列即可:

require 'nokogiri'

doc = Nokogiri::HTML("
<html>
  <body>
    <a href='path/to/foo'>bar</a>
  </body>
</html>
")

doc.at('a')['href'] # => "path/to/foo"

您不需要浪费时间输入 attr(...)