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.
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.
Definition and Usage. The preg_match() function returns whether a match was found in a string.
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.
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 .
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 :
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With