Monday, November 16, 2015

RegEx: Extract tokens from a URL

String url = "http://localhost:8080/dummy/index.jsp?key1=value1&key2=value2;http://localhost:8080/dummy/index.jsp?key2=value3;";

Pattern pattern = Pattern.compile("(key2=)(.+?)(&|;)");

Matcher matcher = pattern.matcher(url);

while (matcher.find()) {
System.out.println(matcher.group(2));
}

Output:
value2
value3

Note: Usually, while creating patterns, if we are interested in groups, we categorize them in parenthesis as shown above. In our example, we have 3 groups, out of which we are interested in group-2.