aloo
aloo

Reputation: 11

Regular expression to convert url parameter string into path

Need regular expression to change below url

abc.aspx?str=blue+lagoon&id=1234 

to

/blog/blue-lagoon/

Upvotes: 1

Views: 394

Answers (2)

zen
zen

Reputation: 13083

in perl:

my $work_url = $original_url; 
$work_url =~ s/\+/-/g;
$url = '/blog/' . do { $work_url =~ m/\bstr=([\w\-]+)\b/; $1} . '/';

works for the example given.

inspired by Ragepotato:

$new_url = '/blog/'
    . sub { local $_ = shift; tr/+/-/; m/\bstr=([\w\-]+)\b/; $1 }->($orig_url)
    . '/';

And an stricter, less greedy regex for Ragepotatos post, untested:

Regex.Match(input.Replace("+", "-"),@"\bstr=(.*?)&").Groups[1].Value

Upvotes: 5

Ragepotato
Ragepotato

Reputation: 1630

C# .NET

string input = "abc.aspx?str=blue+lagoon&id=1234";

string output = "/blogs/" + Regex.Match(input.Replace("+", "-"),@"str=(.*)&").Groups[1].Value + "/";

Upvotes: 2

Related Questions