1

I’m having trouble with a matching expression. I want to extract the "code" parameter from a link I extracted using Nokogiri, so I tried:

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

Unfortunately what is extracted is the entire query string:

?code=768140119

What is the proper way to just get the value of the parameter and nothing else?

5
  • And if you use a.attr("href")[/\?code=(\d+)/, 1]? Or just a.attr("href")[/\d+/] (if there is only 1 sequence of one or more digits)? Commented Sep 13, 2016 at 20:47
  • Also, try a["href"][/\d+/] Commented Sep 13, 2016 at 21:00
  • Can you show the input and the output? Are you really accessing [1] of the match? Commented Sep 13, 2016 at 21:52
  • It does work? rubular.com/r/ED3hgfEzuF. I also tried it on ruby 2.3.1. Commented Sep 13, 2016 at 22:57
  • THe only reason "[/\d+/]" doesn't work is there may be multiple sequences of numbers. The only one I care about is the one following "code=". Commented Sep 14, 2016 at 1:46

1 Answer 1

4

Don't use regular expressions, use a well-tested wheel.

Ruby's 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"}

As for extracting the value of a parameter of a tag, Nokogiri makes it easy, just treat the Node like a hash:

require 'nokogiri'

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

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

You don't need to waste time typing attr(...).

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

2 Comments

THe URL is a relative one (e.g. "../results?code=abcde"). Will this still work with a relative URL?

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.