正则要求,一个字符串长度是2 ,第一位是大写A-L或者是1,3,第二位是大写英文字母或者半角数字另外在Java中怎么调这个正则,比如D1,返回true,X1返回false

解决方案 »

  1.   

    Pattern.matches("[A-L13]{1}[A-Z0-9]{1}", str)
      

  2.   

    楼上正解,另外查matches api 看返回的是什么类型,如果不是boolean,外包一个壳子(造一个方法就成)就是了,让它返回boolean型
      

  3.   


    import java.util.regex.Matcher;
    import java.util.regex.Pattern;public class test { public static void main(String[] args) {

    System.out.println("D1 "+test.mat("D1"));
    System.out.println("X1 "+test.mat("X1"));
    }
    public static boolean mat(String str){
    Pattern p = Pattern.compile("[A-L13][A-Z0-9]");
    Matcher m = p.matcher(str);
    return m.matches();
    }
    }
      

  4.   

    ([A-L]|1|3)([A-Z]|[0-9])
    ============================
    測試代碼
    package test;public class Test {    
        public static void main(String[] args) {
            String[] str = {
                    "AA","JA","1A","39","3=","2A","5F","F9"
                };
    //        String pattern = "^(((0?9)|(1[03-7])):[0-5][0-9])|(11:[0-2][0-9])|(12:[3-5][0-9])$";
            String pattern = "^([A-L]|1|3)([A-Z]|[0-9])$";
    //        String pattern1 = "^(((0?9(?!:00))|(1([03-7]|8(?=:00)))):[0-5][0-9])|(11:[0-2][0-9])|(11:30)|(12(?!:30):[3-5][0-9])$";
            
            for(int i = 0; i < str.length; i++) {
                System.out.printf("%5s  %5s%n",
                        str[i],
                        str[i].matches(pattern)
    //                    str[i].matches(pattern1)
                    );
            }        
        }
    }
    =====================
    測試結果
       AA   true
       JA   true
       1A   true
       39   true
       3=  false
       2A  false
       5F  false
       F9   true
    你試試?