首页 > 解决方案 > 在 Java 中验证特定的字符串模式

问题描述

我想将输入字符串的模式验证为两个数字,然后是三个大写字母,然后是三个数字。

例如:“16FIT146”字符串应该是有效的。

标签: java

解决方案


你可以这个正则表达式

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");
    }
 }

推荐阅读