1

Need regular expression to change below url

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

to

/blog/blue-lagoon/
6
  • in what language? This seems like innapropriate regex to me, more info please. Commented Dec 9, 2009 at 23:25
  • If it is indeed an URL, then abc.aspx?id=1234&str=blue+lagoon is a legal equivalent and should be considered as well. Commented Dec 9, 2009 at 23:25
  • Also, as worded, it is not clear why regex is needed at all here - sounds like a straightforward search & replace. Commented Dec 9, 2009 at 23:27
  • Basically an expression to strip the string between "=" and "&" (For the above example--> blue+laggon) from the url and then add another string to it. Commented Dec 9, 2009 at 23:30
  • I need to pass the Regular expression to a CMS server for doing regex aliasing Commented Dec 9, 2009 at 23:31

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
This might get you close.. Syntax snagged from: radsoftware.com.au/articles/regexsyntaxadvanced.aspx using System.Text.RegularExpressions; Regex exp = new Regex( @"\bstr=([\w\+]+)\b" ); string InputText = "abc.aspx?str=blue+lagoon&id=1234"; MatchCollection MatchList = exp.Matches(InputText); Match FirstMatch = MatchList[0]; Console.WriteLine(FirstMatch.Value);
2

C# .NET

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

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

1 Comment

nicely done. Needs a word boundary on the str and a non greedy capture (.*?) don't you think?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.