2

I would like to parse a string which is basically a URL. I need to check simply that a parameters is passed to it or not.

so http://a.b.c/?param=1 would return true http://a.b.c/?no=1 would return false and http://a.b.c/?a=1&b=2.....&param=2 would return true since param is set

I am guessing that it would involve some sort of regular expression.

geoaxis
  • 1,480
  • 6
  • 25
  • 46
  • possible duplicate of [Parsing query strings in Java](http://stackoverflow.com/questions/1667278/parsing-query-strings-in-java) – dacwe May 20 '11 at 10:49

2 Answers2

8

Java has a builtin library for handling urls: Spec for URL here.

You can create a URL object from your string and extract the query part:

URL url = new URL(myString);
String query = url.getQuery();

Then make a map of the keys and values:

Map params<string, string> = new HashMap<string, string>();
String[] strParams = query.split("&");
for (String param : strParams)  
{  
    String name = param.split("=")[0];  
    String value = param.split("=")[1];  
    params.put(name, value);  
}

Then check the param you want with params.containsKey(key);

There is probably a library out there that does all this for you though, so have a look around first.

verdesmarald
  • 11,646
  • 2
  • 44
  • 60
  • it throws an exception, the URL can be malformed and we should not care as it could be based on an expression which would be expanded later. – geoaxis May 20 '11 at 10:43
  • @geoaxis: Then you would have to do some processing to extract the query string... It depends how 'misformed' your URLs can be (e.g. can they contain unescaped `?`, `&`, `=`, etc.) I would suggest `myString.split("?")[1];` as a first cut. – verdesmarald May 20 '11 at 10:49
  • @dacwe: A well-formed url can't contain & it would contain `%26amp%3B` – verdesmarald May 20 '11 at 10:50
1
String url = "http://a.b.c/?a=1&b=2.....&param=2";
String key = "param";
if(url.contains("?" + key + "=") || url.contains("&" + key + "="))
    return true;
else
    return false;