0

The following gets me one match:

query = http://0.0.0.0:9393/review?first_name=aoeu&last_name=rar
find = /(?<=(\?|\&)).*?(?=(\&|\z))/.match(query)

When I examine 'find' I get:

first_name=aoeu

I want to match everything between a '?' and a '&', so I tried

find = query.scan(/(?<=(\?|\&)).*?(?=(\&|\z))/)

But yet when I examine 'find' I now get:

[["?", "&"], ["&", ""]]

What do I need to do to get:

[first_name=aoeu][last_name=rar]

or

["first_name=aoeu","last_name=rar"]

?

shicholas
  • 6,123
  • 3
  • 27
  • 38

3 Answers3

3

Use String#split.

query.split(/[&?]/).drop(1)

or

query[/(?<=\?).*/].split("&")

But if your real purpose is to extract the parameters from url, then question and its answer.

Community
  • 1
  • 1
sawa
  • 165,429
  • 45
  • 277
  • 381
  • thank you! fwiw to anyone else tripped by this, query.split(/[&?]/).drop(1) results in the second scenario I asked for. – shicholas Sep 26 '12 at 07:06
  • 1
    @shicholas I realized that, and changed my answer, but the original one with your modification may be better. – sawa Sep 26 '12 at 07:08
3

Use other module provided by ruby or rails will make your code more maintainable and readable.

require 'uri'
uri = 'http://0.0.0.0:9393/review?first_name=aoeu&last_name=rar'

require 'rack'
require 'rack/utils'
Rack::Utils.parse_query(URI.parse(uri).query)
# => {"first_name"=>"aoeu", "last_name"=>"rar"}

# or CGI
require 'cgi'
CGI::parse(URI.parse(uri).query)
# => {"first_name"=>["aoeu"], "last_name"=>["rar"]}
halfelf
  • 9,737
  • 13
  • 54
  • 63
0

If you need extract query params from URI, please, check thread "How to extract URL parameters from a URL with Ruby or Rails?". It contains a lot of solutions without using regexps.

Community
  • 1
  • 1