1

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?

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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…

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.