3

I am struggling to find a pattern that will allow me to select the value portion of a Parameter=Value element of a URL string. I would like it to be generic enough that I could replace the 'Parameter' with any term and retrieve its value.

For example, if the URL string is (it always follows this general form):

'http://www.mysite.com/home.aspx?userid=53&transaction=2&viewport=property'

I need to be able to the get value portion of userid or transaction or viewport, or whatever selectively.

Preferably it would be as easy as adding a parameter name and it matching eveything that follows its = to the &. My attempts to make a general purpose match string ... suck.

I cannot use a javascript function or anything, it has to be perl-like regex matching (This is for use with Apache JMeter if you are curious).

I suck at regex :-/ Thanks in advance for any help.

Serialize
  • 491
  • 5
  • 13

3 Answers3

8

In case it has to be a regex,

/userid=([^&]*)/
mpapec
  • 50,217
  • 8
  • 67
  • 127
6

Using a regex to parse the URI may not work for you in all cases: URI components often have characters in them escaped, they may appear multiple times, etc.

You can use Perl's URI module to parse URIs:

use strict;
use warnings;
use URI;
use Data::Dumper;

my $u = URI->new('http://www.mysite.com/home.aspx?userid=53&transaction=2&viewport=property');

my %q = $u->query_form;
print Dumper(\%q), "\n";

The query_form method returns the query string as a hash, making it very easy to extract parameters you're looking for:

print $q{'transaction'}, "\n";
Kyle Burton
  • 26,788
  • 9
  • 50
  • 60
  • The URI will never deviate from the general pattern above, or have any escaped characters (this is an in house app that we develop). I can't use a perl function of any kind, it has to be a regex matching pattern in 'perl compaitable syntax', sorry for the confusion. – Serialize Feb 11 '14 at 22:54
4

Looks like this might work: <variable>=(\w+)
For example: userid=(\w+)

I'm assuming that I WON'T always have an "&" at the end of the value.

As this needs to match a string for a JMeter test, check out the official docs here:
http://jmeter.apache.org/usermanual/regular_expressions.html

I would also use the online perl regex tool here:
http://www.regexplanet.com/advanced/perl/index.html

If you are controlling URL itself, you can probably get away with simply creating 3 regular expression extractors (one for each variable). I bit of a kludge but simpler than trying to to it all at once. Here is an article that has some more concrete examples:
http://community.blazemeter.com/knowledgebase/articles/65150-using-regex-regular-expression-extractor-with-jm

Ophir Prusak
  • 1,437
  • 13
  • 20