java正则表达式简单总结以及个别案例(手机号码,邮箱,座机号码)

记录一下学习历程,方便自己回头看看

首先使用正则表达式的格式是这样

String str="1asdf978";

str.matches("\\d{6,20}");

正则表达式是一种校验字符串的方法,一般来说校验的也就是字符串嘛。像是qq账号密码这样的都不会是int数据类型。

上图是正则表达式的基本书写规则和几则简单的例子

下面是手机号码,邮箱,电话号码的正则实现。

public class RegexTest3 {
    public static void main(String[] args) {
        //目标 校验手机号码 邮箱 电话号码
//        checkPhone();
//        checkEmail();
//        checkTel();


    }

    public static void checkPhone(){
        Scanner sc=new Scanner(System.in);
        while (true) {
            System.out.println("请输入手机号");
            String phoneNumber = sc.next();
            if(phoneNumber.matches("1[3-9]\\d{9}")){
                System.out.println("手机号码正确");
                break;
            }
            else{
                System.out.println("格式有误");
            }
        }
    }
    public static void checkEmail(){
        Scanner sc=new Scanner(System.in);
        while (true) {
            System.out.println("请输入邮箱");
            String email = sc.next();
            //邮箱正则表达式
            //xxxxxxxxxx@xxxx.xxxx.xxxx
            //xxxxxxxxxx@xxxx.xxxx
            if(email.matches("\\w{1,20}@[a-zA-Z0-9&&[^_]]{2,20}(\\.[a-zA-Z0-9&&[^_]]{2,20}){1,2}")){
                System.out.println("邮箱正确");
                break;
            }
            else{
                System.out.println("格式有误");
            }
        }
    }
    public static void checkTel(){
        Scanner sc=new Scanner(System.in);
        while (true) {
            System.out.println("请输入电话号码");
            String tel = sc.next();
            //027-3572457 027
            if(tel.matches("0\\d{2,6}-?\\d{5,20}")){
                System.out.println("电话号码正确");
                break;
            }
            else{
                System.out.println("格式有误");
            }
        }
    }
  
}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

KYLO_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值