简体   繁体   English

Java RegEx - 检查字符串是否以确切的位数结尾

[英]Java RegEx - check if a string ends with an exact number of digits

The Java matches method returns 'true' for all of the following Java matches方法为以下所有方法返回'true'

// 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. 由于s20180122_2有更多数字,我希望第二和第三次检查返回'false',但它们没有。 How do I enforce the exact (8 digits only. No more, no less) match? 我如何强制执行(仅8位数。不多,不少)匹配?

Thanks for your help. 谢谢你的帮助。

This should work: 这应该工作:

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

or if Java regex engine supports \\D group, you can use it instead of [^\\d] 或者如果Java正则表达式引擎支持\\D组,您可以使用它代替[^\\d]

这个正则表达式将验证最后8个字符是yyyyMMdd形式的数字(年份在yyyyMMdd世纪之内:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM