java案例代码16-java正则表达式的使用

java案例代码16-java正则表达式的使用,第1张

java案例代码16-java正则表达式的使用

具体看注释:

具体使用的是字符串中的函数“matches”

matches 

package Templab;

import java.util.Scanner;

public class Regeslab1 {


    public static void main(String[] args) {
//        checkPhone();   //手机格式,正则的监测

//        checkEmain();  //邮箱格式检测
        checkTel();  //手机号的监测

    }


    public static void checkTel(){
        Scanner sc=new Scanner(System.in);

        while (true){
            System.out.println("请输入您的电话号码:");
            String tel=sc.next();

            //判断电话号码的格式是否正确
            //010-12345678   01012345678
            if(tel.matches("0\d{2,6}-?\d{5,20}")){
                System.out.println("格式正确,注册完成!");
                break;


            }else{
                System.out.println("格式有误!");
            }
        }

    }



    public static void checkEmain(){
        Scanner sc=new Scanner(System.in);

        while (true){
            System.out.println("请输入您的注册邮箱:");
            String email=sc.next();

            //判断邮箱的格式是否正确
            // @符号前面1~~30个字符,数字等,@符号后2~~20位字符,后面是“.2~~20个字符",一到2组,类似
            //dsddsds@yahoo.com.cn类似这样的邮箱。
            String emainreg="\w{1,30}@[a-zA-Z0-9]{2,20}(\.[A-Za-z0-9]{2,20}){1,2}";
            if(email.matches(emainreg)){
                System.out.println("邮箱格式正确,注册完成!");
                break;


            }else{
                System.out.println("格式有误!");
            }
        }

    }


    //手机方法检测
    public static void checkPhone(){
        Scanner sc=new Scanner(System.in);

        while (true){
            System.out.println("请输入您的注册收集号码:");
            String phone=sc.next();

            //判断手机号码的格式是否正确
            if(phone.matches("1[3-9]\d{9}")){
                System.out.println("手机号码格式正确,注册完成!");
                break;


            }else{
                System.out.println("格式有误!");
            }
        }

    }

}

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/5437543.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-12-11
下一篇2022-12-11

发表评论

登录后才能评论

评论列表(0条)

    保存