Java—— 正则表达式 练习

需求: 

请编写正则表达式验证用户输入的手机号码是否满足要求。
请编写正则表达式验证用户输入的邮箱号是否满足要求。
请编写正则表达式验证用户输入的电话号码是否满足要求。

验证手机号码
13112345678

13712345667

13945679027

139456790271

验证座机电话号码
020-2324242

02122442

027-42424

0712-3242434

验证邮箱号码
[email protected]

[email protected]

[email protected]

[email protected]

分析与代码:

public class Test7 {
    public static void main(String[] args) {
        //请编写正则表达式验证用户输入的手机号码是否满足要求。
        //请编写正则表达式验证用户输入的邮箱号是否满足要求。
        //请编写正则表达式验证用户输入的电话号码是否满足要求。
        //验证手机号码
        //13112345678 13712345667 13945679027 139456790271
        //验证座机电话号码
        //020-2324242 02122442 027-42424 0712-3242434
        //验证邮箱号码
        //[email protected] [email protected] [email protected] [email protected]

        验证手机号码
        //第一个数字为1,第二个数字为3-9,其余数字为0-1
        String regexMPN = "1[3-9]\\d{9}";
        System.out.println("13112345678".matches(regexMPN));//true
        System.out.println("13712345667".matches(regexMPN));//true
        System.out.println("13945679027".matches(regexMPN));//true
        System.out.println("139456790271".matches(regexMPN));//false

        //验证座机电话号码
        //区号:0开头,其余2位或3位任意数字 0\d{2,3}
        //-:可有可无 -?
        //号码:不能以0开头 其余是任意数字 总长度5-10位 [1-9]\d{4,9}
        String regexLPN = "0\\d{2,3}-?[1-9]\\d{4,9}";
        System.out.println("020-2324242".matches(regexLPN));//true
        System.out.println("02122442".matches(regexLPN));//true
        System.out.println("027-42424".matches(regexLPN));//true
        System.out.println("0712-3242434".matches(regexLPN));//true

        //验证邮箱号码
        //@左边:任意数字字母下划线,至少一位 \w+
        //@:必须出现 @
        //@右边:
        //      .左边:任意数字字母,2-6位 [\w&&[^_]]{2,6}
        //      .:必须出现 \.
        //      .右边:任意字母,2-3位 [a-zA-Z]{2,3}
        //      .及.右边的部分可以出现1次或2次 (\.[a-zA-Z]{2,3}){1,2}

        String regexMBN = "\\w+@[\\w&&[^_]]{2,6}(\\.[a-zA-Z]{2,3}){1,2}";
        System.out.println("[email protected]".matches(regexMBN));//true
        System.out.println("[email protected]".matches(regexMBN));//true
        System.out.println("[email protected]".matches(regexMBN));//true
        System.out.println("[email protected]".matches(regexMBN));//true
        
    }
}

 

你可能感兴趣的:(正则表达式,java,intellij-idea,开发语言)