Java 如何检查字符串是否与特定格式匹配?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18259644/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:47:57  来源:igfitidea点击:

How to check if a string matches a specific format?

javastring

提问by maysi

I want to check if a string matches the following format:

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

"00-00"

There should be no whitespace in the String, only 2 numbers before the dash and 2 numbers after the dash.

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

What's the best way to do this?

做到这一点的最佳方法是什么?

采纳答案by arshajii

You can use matches():

您可以使用matches()

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

If you're going to be doing this sort of validation a lot, consider pre-compiling the regex:

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

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

You can then use p.matcher(str).matches(). See the Patternclass for more details.

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