Java、JavaScript以及python使用正则表达式校验用户的输入

文章目录

java

package com;

/**
 * java 使用正则表达式校验用户输入的账号和密码。
 * 账号要求:11为数字。
 * 密码要求:字母数字下划线,长度8-16。
 */
public class Main {

    public static void main(String[] args) {
        // 假设用户输入的手机号
        String mobile = "12345678901";
        // 假设用户输入的密码
        String password = "11111111";

        // 登录
        String result = login(mobile, password);

        if (!"SUCCESS".equals(result))
            System.out.println(result);
        else
            System.out.println("登录成功");
    }

    public static String login(String mobile,String password){

        // 验证手机号是不是11位
        if (mobile.length()!= 11) return "手机号长度错误";

        // 验证密码是不是8 ~ 16位
        int len = password.length();
        if (len < 8 || len > 16) return "密码长度有误";

        // 设置手机号的匹配规则,(这里的匹配规则非常简单,不适用于真正的业务场景:手机号的前面三位数字比较特殊。)
        String mobileRegex = "[1-9][0-9]{10}";

        // 判断是不是手机号:第一位数字不能为0
        if (!mobile.matches(mobileRegex)) return "手机号输入错误";

        // 设置密码的匹配规则
        String pwdRegex = "[a-zA-Z0-9_]{"+len+"}";
        // 判断用户输入的是不是字母数字下划线
        if (!password.matches(pwdRegex)) return "密码只能是字母数字下划线";

        return "SUCCESS";
    }

}

python

import re


def login(mobile, password):
    if len(mobile) != 11:
        return "手机号格式错误"

    mobile_pattern = re.compile(r"[1-9][0-9]{10}")
    reply = re.match(mobile_pattern, mobile)
    if reply:
        pass
    else:
        return "手机号格式有误"

    length = len(password)
    if length < 8 | length > 16:
        return "密码长度有无"
    pwd_pattern = re.compile(r"[a-zA-Z0-9_]{" + str(length) + "}")

    reply = re.match(pwd_pattern, password)

    if reply:
        pass
    else:
        return "密码只能是字母数字下划线"

    return "SUCCESS"


if __name__ == '__main__':

    mobile = "12345678901"

    password = "23ded22d#"

    result = login(mobile, password)

    if "SUCCESS" != result:
        print(result)
    else:
        print("登录成功")

JavaScript

<script>
    // 假设用户输入
    let mobile = "12345678901"
    let password = "sf32r23fqad"

    // 校验手机号长度
    if (mobile.length !== 11){
        console.log("手机号错误")
    }

    // 校验密码长度
    let pwdLen = password.length
    if (pwdLen <8 || pwdLen > 16){
        console.log("密码长度为 8 ~ 16 位字符")
    }

    // 校验手机号是否都是数字,且第一位数字不是0
    let mobileRegex = /[1-9][0-9]{10}/
    if (!mobileRegex.test(mobile)){
        console.log("手机号有误")
    }

    // 校验密码是不是都是由 字母数字下划线组成
    let pwdRegex = new RegExp("[0-9a-zA-Z]{"+pwdLen+"}")
    if (!pwdRegex.test(password)){
        console.log("密码只能是字母数字下划线")
    }
</script>
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值