如何检查字符串是否与特定格式匹配? [英] How to check if a string matches a specific format?
本文介绍了如何检查字符串是否与特定格式匹配?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想检查一个字符串是否仅采用以下格式:
I want to check if a string only mytches the following format:
"00-00"
字符串中不应有空格,破折号前面只有2个数字,破折号后面只有2个数字。
There should be no whitespaces in the String and only 2 numbers before the dash and 2 numbers after the dash.
最好的方法是什么?
推荐答案
你可以用 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
然后你可以使用 p.matcher (STR).matches()
。请参阅 模式
类了解更多详情。
You can then use p.matcher(str).matches()
. See the Pattern
class for more details.
这篇关于如何检查字符串是否与特定格式匹配?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文