Reputation: 29806
I need to check if a given String ends with a Regular Expression String. I have written the following code:
public static void main(String[] args) {
String str = "wf-008-dam-mv1";
String regex = "mv(\\d)?$";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(str);
if(matcher.find() && matcher.end() == str.length()) {
System.out.println("Ends with true");
} else {
System.out.println("Ends with false");
}
}
Here the str
can ends with or without number. Is it a good way to do it?
Upvotes: 1
Views: 4076
Reputation: 298103
Since the $
anchor already ensures that the pattern must match at the end, a simple find
is enough; you don’t need to verify the end of the match. If you prepend your pattern with .*
you can use matches
rather than find
which allows you to remove the entire boilerplate:
boolean endsWith="wf-008-dam-mv1".matches(".*mv(\\d)?$");
System.out.println("Ends with "+endsWith);
That’s all you need…
Upvotes: 3
Reputation: 6855
matcher.find()
does the job for you and no need to check with matcher.end() == str.length()
API says
If the match succeeds then more information can be obtained via the start, end, and group methods
Upvotes: 1
Reputation: 500167
That's a pretty reasonable way to do it, except that the matcher.end() == str.length()
check is redundant. The $
regex anchor already takes care of that.
Upvotes: 4