使用Java中自带类的正则的表达式进行格式匹配

Java 中的自带Pattern 类可以进行信息的匹配。

常用的使用方式如下:


    private final Pattern emailRegex = Pattern.compile("^[_a-z0-9-]+([.][_a-z0-9-]+)*@[a-z0-9-]+([.][a-z9-9-]+)*$");
    private final Pattern passwordRegex = Pattern.compile("^\\w{8,16}$");
    private final Pattern usernameRegex = Pattern.compile("^\\w{1,16}$");

// Pattern.complie 这个方法的作用:complie 中文意思是编译。这里的就是将给定的正则表达式编译为带有给定的标志的模式。
//完成编译给定的表达式后,需要进行输入匹配。
   /*格式匹配 一般情况下,在开发的过程中,会对用户登录注册等功能能做一些细节操作。*/
    private boolean validateEmail(String email){
        return email!=null && emailRegex.matcher(email).find();
    }
    private boolean validateUsername(String username){
        return username!=null && usernameRegex.matcher(username).find();
    }
    private boolean validatePassword(String password){
        /*matcher:创建一个匹配容器,匹配给定的输入与此模式 */
        return password!= null && passwordRegex.matcher(password).find();
    }

或许可能会上述部分代码中稍带有些疑惑 find();和matcher()的解析

    //查看源码后,给予以下的解释。

//* form,to 为搜索区域的范围。类型均为int。
//last first 为int 类型为最后的匹配范围。 取值 分别为 0,-1;
    public boolean find() {
        int nextSearchIndex = last;
        if (nextSearchIndex == first)
            nextSearchIndex++;

        //如果搜索在下个区域开始之前,就在区域开始
        if (nextSearchIndex < from)
            nextSearchIndex = from;

        // 如果下一次搜索开始于区域之外,则就会失败。
        if (nextSearchIndex > to) {
            for (int i = 0; i < groups.length; i++)
                groups[i] = -1;
            return false;
        }
//这里返回的Mather 中search 方法。方法的类型是boolean
        return search(nextSearchIndex);
    }





//matcher() 方法;创建一个匹配器,匹配给定的输入与此模式。参数 input- 要匹配的字符序列 
    public Matcher matcher(CharSequence input) {
        if (!compiled) {
            synchronized(this) {
                if (!compiled)
                    compile();
            }
        }
        Matcher m = new Matcher(this, input);
        return m;
//返回结果是新的
    }

对于部分的解释可能还未到位,会在后续的学习过程中继续深入研究。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值