0

How can I extract a param value using a regex, like the mver param from this string:

"/maze/action.xml?mver=66381&cid=474&melu=0&osName=Windows%208&dbv=38&ucnt=19"

I want to extract the mver param using

mver\=(.*?)\&

How can I make it capture it even if it's the last param (no trailing ampersand)

Thank you

kambi
  • 3,291
  • 10
  • 37
  • 58

3 Answers3

4

Here is a simple way for this -

2.1.0 :001 > require 'uri'
 => true 
2.1.0 :002 > uri = URI("/maze/action.xml?mver=66381&cid=474&melu=0&osName=Windows%208&dbv=38&ucnt=19")
 => #<URI::Generic:0x00000103011c98 URL:/maze/action.xml?mver=66381&cid=474&melu=0&osName=Windows%208&dbv=38&ucnt=19> 
2.1.0 :003 > require 'cgi'
 => true 
2.1.0 :004 > CGI::parse(uri.query)
 => {"mver"=>["66381"], "cid"=>["474"], "melu"=>["0"], "osName"=>["Windows 8"], "dbv"=>["38"], "ucnt"=>["19"]} 
2.1.0 :005 > CGI::parse(uri.query)['mver']
 => ["66381"] 
2.1.0 :006 > 

Have a look at CGI::parse and this example.

Arup Rakshit
  • 116,827
  • 30
  • 260
  • 317
0

If you are using Ruby 2 and the parameter is all digits, this short regex is all you need:

mver=\K\d+

(No capturing groups needed, the regex matches the digits directly).

If the parameter can contain other characters than digits, then you can use this variation:

mver=\K\[^&]+

See online demo

How does it work?

  1. We match the literal mver=
  2. \K tells the engine to drop what we have matched so far, i.e. mver=, from the string that will be returned
  3. We match any number of digits. These digits will be the final match to be returned.
zx81
  • 41,100
  • 9
  • 89
  • 105
0

Here is a regex: if you want to capture both param and value.

mver=(((?!&).)*) 

for only value.

(?<=mver=)(((?!&).)*)
Dhrubajyoti Gogoi
  • 1,265
  • 10
  • 18