String.matches internally delegates to Matcher.matches.
public boolean matches(String regex) {
return Pattern.matches(regex, this);
}
public static boolean matches(String regex, CharSequence input) {
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(input);
return m.matches();
}
If you are reusing the Pattern object then there will be some performance benefit. Also when using Pattern/Matcher you can group your regular expressions and get the matching parts.
The bottomline is if you have a regex that you will use only once and you don't need to parse your string to get matching parts then use either. But if you are going to use the same regex against multiple strings or you need parts of the String based on regex create a Pattern and get Matcher using it.
String.matches
internally calls Pattern.matches(regex, str)
. The problem with it is that each time you call it you recompile the pattern, which cost some resources.
It is better to compile your pattern once, then try to match it against all the Strings you want. I personally use a Patterns class containing all my pattern in my app declared as final and static
Read full article from java - What's the difference between String.matches and Matcher.matches? - Stack Overflow
No comments:
Post a Comment