3

The Java matches method returns 'true' for all of the following

// check if a string ends with an exact number of digits (yyyyMMdd 8 digits)

    String s20180122_1 = "fileNamePrefix_20171219";
    String s20180122_2 = "fileNamePrefix_20171219131415111";

    System.out.println(s20180122_1.matches(".*\\d{8}$"));
    System.out.println(s20180122_2.matches(".*\\d{8}$"));
    System.out.println(s20180122_2.matches(".*\\d{8,8}$"));

Since the s20180122_2 has more digits I expect the 2nd and 3rd checks to return 'false', but they don't. How do I enforce the exact (8 digits only. No more, no less) match?

Thanks for your help.

0

2 Answers 2

3

This should work:

.*[^\d]\d{8}$

or if Java regex engine supports \D group, you can use it instead of [^\d]

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

5 Comments

Very interesting. It works. Can you explain the logic please?
@badbee, the main issue with you regex that it doesn't set the left boundary of the digit part, which in your example is _. From your example you can use this regex: .*_\d{8}$. To make it a bit more generic you can use [^\d] (any character that is not a digit) instead of _ character.
Thank you for the explanation.
This regex did not work as expected on oracle. returned true with 9 digits. Still working at it. I actually want to test for ending in 6 or 8 digits.
This got it. Couldn't edit my previous comment. .*[:digit:{6|8}]$
1

This regex would validate that the last 8 characters are digits in yyyyMMdd form (and the year is within the 20th-21st centuries:

.*[^\d](19|20)\d{2}(0[1-9]|1[0-2])(0[1-9]|[12]\d|3[01])$

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.