Differences between Jakarta Regexp and Java 6 java.util.regex

I am migrating from Jakarta Regexp to the standard Java 6 regular expression package java.util.regex . I noticed the following difference when I did not indicate the beginning of ^ and end $ in regexp: Jakarta Regexp returns true when regexp matches part of the string, while the Java 6 package java.util.regex does not matter:

 String regexp = "\\d"; String value = "abc1abc"; Pattern pattern = Pattern.compile(regexp); Matcher matcher = pattern.matcher(value); result = matcher.matches(); // returns false 

Returns false , whereas:

 RE re = new RE(regexp); re.match(value); // returns true 

Returns true .

What is the reason for this? I was thinking about a greedy / lazy match, but this does not seem like JDK 6 is not suitable.

Are there any other differences that I should be aware of?

+4
source share
2 answers

The java.util.regex.Matcher.matches () method will try to match the entire input string with your regular expression, which will be false .

If you want to find the template in the input line, you will need to use java.util.regex.Matcher.find () :

  result = matcher.find(); // returns true 
+5
source

Use find() instead of matches() . It functions exactly as you expect.

+2
source

All Articles