Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP's `preg_match_all` functionality in Java

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.

like image 740
Leo Avatar asked Oct 01 '10 18:10

Leo


People also ask

What is Preg_match_all?

The preg_match_all() function returns the number of matches of a pattern that were found in a string and populates a variable with the matches that were found.

What is Preg_match function?

Definition and Usage. The preg_match() function returns whether a match was found in a string.

Which of the following is correct about preg_ match() function mcq?

Explanation: The function preg_match() searches string for pattern and it returns true if pattern exists, and false otherwise. The function returns 1 if search was successful else returns 0.

Which of the following call to Preg_match will return false?

preg_match() returns 1 if the pattern matches given subject , 0 if it does not, or false on failure. This function may return Boolean false , but may also return a non-Boolean value which evaluates to false .


2 Answers

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 :

  • Javadoc - Matcher.group()
like image 70
Colin Hebert Avatar answered Oct 13 '22 23:10

Colin Hebert


Java Pcre is a project that provides a Java implementation of all the php pcre funcions. You can get some ideas from there. Check the project https://github.com/raimonbosch/java.pcre

like image 26
raimonbosch Avatar answered Oct 13 '22 23:10

raimonbosch