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.

Alfabravo
  • 7,493
  • 6
  • 46
  • 82
badbee
  • 45
  • 4

2 Answers2

3

This should work:

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

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

Kirill Polishchuk
  • 54,804
  • 11
  • 122
  • 125
  • 1
    Very interesting. It works. Can you explain the logic please? – badbee Jan 22 '18 at 22:40
  • @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. – Kirill Polishchuk Jan 22 '18 at 22:46
  • Thank you for the explanation. – badbee Jan 23 '18 at 14:14
  • 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. – slestak Jun 12 '19 at 18:03
  • This got it. Couldn't edit my previous comment. .*[:digit:{6|8}]$ – slestak Jun 12 '19 at 18:15
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])$
GalAbra
  • 5,048
  • 4
  • 23
  • 42