I'm relatively new to regular expressions and could use some help. Can someone provide a regex (I'm using Perl) to extract a query string from a URL? I have tried the following but get an empty string:
my $string = 'http://www.google.com?queryArg1=1&queryArg2=2';
$string =~ s/^(.*)?//;
Ideally this example would provide the following string: queryArg1=1&queryArg2=2
More awesome if you could turn this into a hash:
my $hash = {queryArg1 => 1,
queryArg2 => 2};
Thanks for your help!
use URI qw( );
my $uri = 'http://www.google.com?queryArg1=1&queryArg2=2';
$uri = URI->new($uri);
my $query = $uri->query();
say $query;
my %form = $uri->query_form();
say "$_: $form{$_}"
for keys(%form);
Using a flat hash obviously can't handle repeated arguments, and loses parameter order. Loading URI::QueryParam adds more methods to URI objects that you'd find useful if you need that kind of stuff.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With