【问题标题】:How to check if a string matches a specific format?如何检查字符串是否与特定格式匹配?
【发布时间】:2013-08-15 18:54:44
【问题描述】:

我想检查一个字符串是否符合以下格式:

"00-00"

字符串中不能有空格,破折号前只有 2 个数字,破折号后只有 2 个数字。

最好的方法是什么?

【问题讨论】:

    标签: java string


    【解决方案1】:

    你可以使用matches():

    str.matches("\\d{2}-\\d{2}")
    

    如果您要经常进行此类验证,请考虑预编译正则表达式:

    Pattern p = Pattern.compile("\\d{2}-\\d{2}");  // use a better name, though
    

    然后您可以使用p.matcher(str).matches()。有关详细信息,请参阅 Pattern 类。

    【讨论】:

    • 如果模式是“A-1232-AB”?
    • pattern 应该是"^\\d{2}-\\d{2}$",请您编辑一下..
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-12-19
    • 2018-04-03
    • 2010-12-08
    • 2016-10-03
    • 1970-01-01
    • 2016-06-07
    • 2012-09-17
    相关资源
    最近更新 更多