tags:

views:

339

answers:

4

Hello!

I am looking for a single perl compatible regex that would parse strings of the form:

param1=value1&...&param2=value2&...

and extract values for param1 and param2 only. But

  1. param2 may precede param1
  2. There may be no param1 or param2
  3. param1 or param2 (or both) may have empty values, i.e. param1=&...
+1  A: 

/(.*?)=(.*?)&/ looping through and capturing $1 and $2 should work

ennuikiller
A single . matches any one character this would work if the parameters and values are all a single character.
Copas
yeah somehow the * got lost of course I meant (.*?) question mark for lazy evaluation
ennuikiller
Markdown bit you, * means italicise to it and it nuked it. Downvote deleted.
Kent Fredric
+3  A: 

I wouldn't bother writing your own request parser. Just use CGI.pm.

Dave Webb
Seconded. I went looking for an old snipped that parse query strings by hand, and found that I'd long ago converted my scripts to use CGI.pm
Dave W. Smith
The problem is that it's not actually perl, it's C++. I just use perl-compatible regular expressions
Konstantin
+2  A: 
/[?&]([^=]+)=([^=&]+)/g

This will match any non = character separated by an = and put them into $1 and $2.

or...

my %argsHash = split(/=|&/, $args);

This will give you a hash with parameters and values which appears to work well, but CGI.pm is all around a better idea.

Copas
missing close paren for 2nd match group
glenn jackman
Alan Moore
Thanks to both, +1
Copas
A: 

If this is for C++, consider using an existing CGI library that parses the query parameters for you instead of reinventing that sort of thing yourself.

One such library is cgic, a CGI library for C: http://www.boutell.com/cgic/#functions

a paid nerd