0

I like to write a java utility method that returns paramValue for paramName in specified query string

Pattern p = Pattern.compile("\\&?(\\w+)\\=  (I don't know what to put here) ");

public String getParamValue(String entireQueryString, String paramName)
{
    Matcher m = p.matcher(entireQueryString);
    while(m.find()) {
        if(m.group(1).equals(paramName)) {
            return m.group(2);
        }
    }
    return null;
}

I will be invoking this method from my servlet,

    String qs = request.getQueryString(); //action=initASDF&requestId=9078-32&redirect=http://www.mydomain.com?actionId=4343
    System.out.println(getParamValue(qs, "requestId"));

The output should be, 9078-32

krishna
  • 807
  • 2
  • 11
  • 19
  • 2
    Why can't you use `request.getParameter("requestId")`, since you obviously have an `HttpServletRequest`? Reimplementing a query parser using a regex doesn't seem like the most productive thing to do... – Frank Pavageau Sep 18 '12 at 11:29

3 Answers3

1

you can use a regex negated group. See this other SO question: Regular Expressions and negating a whole character group

You'll need to get everything except a &.

Community
  • 1
  • 1
Augusto
  • 28,839
  • 5
  • 58
  • 88
1

Use the proper API to do it: request.getParameter("requestId")

Frank Pavageau
  • 11,477
  • 1
  • 43
  • 53
0

Could you split the string based on ampersands (&) and then search the resulting array for the key (look upto the equals sign).

Here's a link to String.split(): http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#split%28java.lang.String%29

Here's the type of thing I'm talking about:

private static final String KEY_VALUE_SEPARATOR = "=";
private static final String QUERY_STRING_SEPARATOR = "&";

public String getParamValue(String entireQueryString, String paramName) {
    String[] fragments = entireQueryString.split(QUERY_STRING_SEPARATOR);
    for (String fragment : fragments){
        if (fragment.substring(0, fragment.indexOf(KEY_VALUE_SEPARATOR)).equalsIgnoreCase(paramName)){
            return fragment.substring(fragment.indexOf(KEY_VALUE_SEPARATOR)+1);
        }
    }
    throw new RuntimeException("can't find value");
}

The Exception at the end is a pretty rubbish idea but that's not really the important part of this.

Tom Saleeba
  • 4,031
  • 4
  • 41
  • 36