tags:

views:

106

answers:

2

Need regular expression to change below url

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

to

/blog/blue-lagoon/

Appreciate all your help.

+5  A: 

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
zen
Can you give this in C#.net
aloo
Thanks for the answer
aloo
You're welcome. I'm sorry I don't know C#.net syntax yet or I'd be happy to post. I'm sure the regex would look similar, but the invocation..? I'll read up a bit and see if I can wing it w/o a compiler.
zen
This might get you close.. Syntax snagged from: http://www.radsoftware.com.au/articles/regexsyntaxadvanced.aspxusing System.Text.RegularExpressions;Regex exp = new Regex( @"\bstr=([\w\+]+)\b" ); string InputText = "abc.aspx?str=blue+lagoon MatchCollection MatchList = exp.Matches(InputText); Match FirstMatch = MatchList[0]; Console.WriteLine(FirstMatch.Value);
zen
+2  A: 

C# .NET

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

string output = "/blogs/" + Regex.Match(input.Replace("+", "-"),@"str=(.*)&").Groups[1].Value + "/";
Ragepotato
nicely done. Needs a word boundary on the str and a non greedy capture (.*?) don't you think?
zen
True, good catch
Ragepotato