我想验证输入字符串的模式为两个数字,然后是三个大写字母,然后是三个数字。
例如:“16FIT146”字符串应该有效。
您可以使用正则表达式实现此目的
public class Test {
public static void main(String args[]) {
String patternStr = "\\d{2}\\w{3}\\d{3}";
Pattern pattern = Pattern.compile(patternStr);
String input = "16FIT146";
Matcher matcher = pattern.matcher(input);
if (!matcher.matches()) {//invalid input
System.out.println("Invalid");
} else {//valid input
System.out.println("Valid");
}
}
}
你可以这个正则表达式
String pattern = "^[0-9]{2}[A-Z]{3}[0-9]{3}$";
if (str.matches(pattern)) {
// something here.
}
例
public static void main(String []args){
matches("16FIT146");
matches("anything");
}
public static void matches(String str) {
String pattern = "^[0-9]{2}[A-Z]{3}[0-9]{3}$";
if (str.matches(pattern)) {
System.out.println("matches");
} else {
System.out.println("not matches");
}
}