JAVA foundation (Regular expressions overview)

1, the regular expression

  • It refers to a string used to describe a single or series of line matching a string of grammar rules. It is actually a rule. It has its own special applications.

  • Role: for example, registered mail, mail user name and password, usually to limit the length of this thing is to limit the length of the regular expression to do

 

 

2, case presentations

[1] needs:

  • Check qq number.

  • Requirements must be 5-15 digits

  • Can not begin with 0

  • Must all be digital

[2] Non-Regular Expression

/*

     * 需求:校验qq号码.

     * 1:要求必须是5-15位数字

     * 2:0不能开头

     * 3:必须都是数字

     * 校验qq

     * 1,明确返回值类型boolean

     * 2,明确参数列表String qq

     */

    public static boolean checkQQ(String qq) {

        boolean flag = true;                    //如果校验qq不符合要求就把flag置为false,如果符合要求直接返回

        

        if(qq.length() >= 5 && qq.length() <= 15) {

            if(!qq.startsWith("0")) {

                char[] arr = qq.toCharArray();    //将字符串转换成字符数组

                for (int i = 0; i < arr.length; i++) {

                    char ch = arr[i];            //记录每一个字符

                    if(!(ch >= '0' && ch <= '9')) {

                        flag = false;            //不是数字

                        break;

                    }

                }

            }else {

                flag = false;                    //以0开头,不符合qq标准

            }

        }else {

            flag = false;                        //长度不符合

        }

        return flag;

    }

 

[3] Regular Expression

    public static void main(String[] args) {

        System.out.println(checkQQ("012345"));

        System.out.println(checkQQ("a1b345"));

        System.out.println(checkQQ("123456"));

        System.out.println(checkQQ("1234567890987654321"));

        

        String regex = "[1-9]\\d{4,14}";//确定长度。确定数字范围

        System.out.println("2553868".matches(regex));

        System.out.println("012345".matches(regex));

        System.out.println("2553868abc".matches(regex));

    }

 

Guess you like

Origin blog.csdn.net/Cricket_7/article/details/92802979