views:

43

answers:

1

In PHP if we need to match a something like, ["one","two","three"], we could use the following regular expression with preg_match.

$pattern = "/\[\"(\w+)\",\"(\w+)\",\"(\w+)\"\]/"

By using the parenthesis we are also able to extract the words one, two and three. I am aware of the Matcher object in Java, but am unable to get similar functionality; I am only able to extract the entire string. How would I go about mimicking the preg_match behaviour in Java.

+4  A: 

With a Matcher, to get the groups you have to use the Matcher.group() method.

For example :

Pattern p = Pattern.compile("\\[\"(\\w+)\",\"(\\w+)\",\"(\\w+)\"\\]");
Matcher m = p.matcher("[\"one\",\"two\",\"three\"]");
boolean b = m.matches();
System.out.println(m.group(1)); //prints one

Remember group(0) is the same whole matching sequence.

Example on ideone


Resources :

Colin Hebert