Tapas Bose
Tapas Bose

Reputation: 29806

Good way to check if a String ends with a Regex String

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

Answers (3)

Holger
Holger

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

Vinay Veluri
Vinay Veluri

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

NPE
NPE

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

Related Questions