Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to extract Query String

Tags:

regex

perl

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!

like image 741
lots_of_questions Avatar asked Jan 26 '26 12:01

lots_of_questions


1 Answers

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.

like image 114
ikegami Avatar answered Jan 28 '26 04:01

ikegami