tags:

views:

235

answers:

4

I need to pull a variable out of a URL or get an empty string if that variable is not present.

Pseudo code:

String foo = "http://abcdefg.hij.klmnop.com/a/b/c.file?foo=123&zoo=panda";
String bar = "http://abcdefg.hij.klmnop.com/a/b/c.file";

when I run my regex I want to get 123 in the first case and empty string in the second.

I'm trying this as my replace .*?foo=(.*?)&?.* replacing this with $1 but that's not working when foo= isn't present.

I can't just do a match, it has to be a replace.

A: 

I think you need to do a match, then a regex. That way you can extract the value if it is present, and replace it with "" if it is not. Something like this:

if(foo.match("\\?foo=([^&]+)")){
  String bar = foo.replace("\\?foo=([^&]+)", $1);
}else{
  String bar = "";
}

I haven't tested the regex, so I don't know if it will work.

Marius
A: 

In perl you could use this:

s/[^?*]*\??(foo=)?([\d]*).*/$2/

This will get everything up to the ? to start, and then isolate the foo, grab the numbers in a group and let the rest fall where they may.

akf
A: 

There's an important rule when using regular expressions : don't try to put unnecessary processing into it. Sometimes things can't be done only by using one regular expression. Sometimes it is more advisable to use the host programming language.

Marius' answer makes use of this rule : rather than finding a convoluted way of replacing-something-only-if-it-exists, it is better to use your programming language to check for the pattern's presence, and replace only if necessary.

Altherac
+1  A: 

You can try this:

[^?]+(?:\?foo=([^&]+).*)?

If there are parameters and the first parameter is named "foo", its value will be captured in group #1. If there are no parameters the regex will still succeed, but I can't predict what will happen when you access the capturing group. Some possibilities:

  • it will contain an empty string
  • it will contain a null reference, which will be automatically converted to
    • an empty string
    • the word "null"
  • your app will throw an exception because group #1 didn't participate in the match.

This regex matches the sample strings you provided, but it won't work if there's a parameter list that doesn't include "foo", or if "foo" is not the first parameter. Those options can be accommodated too, assuming the capturing group thing works.

Alan Moore