测试java中字符串中字符和数字的特定数字顺序

时间:2012-01-20 15:43:42

标签: java string string.format

我正在尝试做的是验证一些输入,以便输入必须以2个字母开头,后跟3个数字,但我找不到测试字符串的方法

 boolean test;
 String str;
 str.format ("%s%s%d%d%d") //used this to give what the format was and was going to use it with a boolean, tried it in an if statement such as

if str.format = ("%s%s%d%d%d") then
{
 test = true
}
else
{
 test = false
}

我想知道为了达到这个目的我该做些什么?

1 个答案:

答案 0 :(得分:2)

听起来你想要一个正则表达式......

// Do this once and cache it...
Pattern pattern = Pattern.compile("\\p{Alpha}{2}\\d{3}");

// Then test it:
boolean test = pattern.matcher(str).lookingAt();

有关详细信息(以及\p{Alpha}的替代方法),请参阅Pattern documentation