-5

In ruby I have string that looks like this:

"\/v1\/195900\/patients?DEPARTMENTID=162&GUARANTORCOUNTRYCODE3166=1&offset=20"

how can I extract offset value from this string with regular expressions?

Mateusz Urbański
  • 7,352
  • 15
  • 68
  • 133

2 Answers2

3

It doesn't satisfy your requirement to use a regex, but here is a way:

uri = "\/v1\/195900\/patients?DEPARTMENTID=162&GUARANTORCOUNTRYCODE3166=1&offset=20"

require "uri"
URI.decode_www_form(URI(uri).query).assoc("offset").last
# => "20"

or

URI.decode_www_form(URI(uri).query).to_h["offset"]
# => "20"
sawa
  • 165,429
  • 45
  • 277
  • 381
2

Assuming offset will always be present as offset= and it will always be a numeric value

str = "\/v1\/195900\/patients?DEPARTMENTID=162&GUARANTORCOUNTRYCODE3166=1&offset=20"
str.scan(/offset=(\d+)/)
#=> [["20"]]
shivam
  • 16,048
  • 3
  • 56
  • 71
  • 1
    You can use a *positive lookbehind* to avoid the nested array: `str.scan(/(?<=offset=)\d+/)`, or - since there is probably only one "offset" - just `str[/(?<=offset=)\d+/]` – Stefan Feb 17 '16 at 14:27