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>
posted @   wbnyua  阅读(49)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 三行代码完成国际化适配,妙~啊~
· .NET Core 中如何实现缓存的预热?
点击右上角即可分享
微信分享提示