2

I need a help finding java regex pattern to get one query information from the URI. For instance URI here is

"GET /6.2/calculateroute.xml?routeattributes=sm,wp,lg,bb&legattributes=mn&maneuverattributes=ac,po,tt,le,-rn,-sp,-di,no,nu,nr,sh&instructionFormat=html&language=en_US&mode=fastest;car;traffic:default&waypoint0=37.79548,-122.392025&waypoint1=36.0957717,-115.1745167&resolution=786&app_id=D4KnHBzGYyJtbM8lVfYX&token=TRKB7vnBguWLam5rdWshTA HTTP/1.1"

I need to extract 4 value out of it which I manage to do it:

GET

/6.2/calculateroute.xml

routeattributes=sm,wp,lg,bb&legattributes=mn&maneuverattributes=ac,po,tt,le,-rn,-sp,-di,no,nu,nr,sh&instructionFormat=html&language=en_US&mode=fastest;car;traffic:default&waypoint0=37.79548,-122.392025&waypoint1=36.0957717,-115.1745167&resolution=786&app_id=D4KnHBzGYyJtbM8lVfYX&token=TRKB7vnBguWLam5rdWshTA

HTTP/1.1

Now the question is how do I write a regex for app_id value from the query string. Note app_id do not appear in all the pattern, so it should be generic and regex should not fail if app_id is missing. Please help...

2
  • can you give a sample string from which app_id id to be extracted? [app_id]* means 0 or more times maybe this will help Commented Nov 2, 2012 at 10:44
  • 1
    Does it have to be a regex? Could you use an existing helper method instead such as this one from Apache HTTPClient? Commented Nov 2, 2012 at 10:44

1 Answer 1

2

Your question can be simplified to: "How do I extract an optional query parameter from a string". Here's how:

String appId = input.replaceAll("(.*(app_id=(\\w+)).*)|.*", "$3");

The appId variable will contain the app_id value if it's present or be blank otherwise.

Here's some test code with the code bundled as a utility method:

public static String getParameterValue(String input, String parameter) {
    return input.replaceAll("(.*("+parameter+"=(\\w+)).*)|.*", "$3"));
}

public static void main(String[] args) {
    String input1 = "foo=bar&app_id=D4KnHBzGYyJtbM8lVfYX&x=y";
    String input2 = "foo=bar&XXXXXX=D4KnHBzGYyJtbM8lVfYX&x=y";

    System.out.println("app_id1:" + getParameterValue(input1, "app_id"));
    System.out.println("app_id2:" + getParameterValue(input2, "app_id"));
}

Output:

app_id1:D4KnHBzGYyJtbM8lVfYX
app_id2:
Sign up to request clarification or add additional context in comments.

1 Comment

This is regex pattern ^(([^:/?#]+):)?(//([^/?#]*))?([^?#]*)(?([^#]*))?(#(.*))?

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.