我有一个Javascript regex用于密码验证:
// Validates password with
// — No white spaces
// — At least one upper case English letter, (?=.*?[A-Z])
// — At least one lower case English letter, (?=.*?[a-z])
// — At least one digit, (?=.*?[0-9])
// — Minimum eight in length .{8,} (with the anchors)
const passwordRegex = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{6,10}$/;我正在尝试使用regex库将其转换为Rust正则表达式;但它似乎不支持展望:https://docs.rs/regex/latest/regex/
use regex::Regex;
pub fn validate_password(string: &str) -> bool {
let regex_no_whitespaces = Regex::new(r"^\s*\S+\s*$").unwrap();
let regex_password = Regex::new(r"^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9]).{6,10}$").unwrap();
let password_valid = regex_password.is_match(&string);
let password_has_no_whitespaces = regex_no_whitespaces.is_match(&string);
let is_valid = password_valid && password_has_no_whitespaces;
return is_valid;
}在没有前瞻性的情况下验证具有多个条件的字符串的常见方法是什么?
编辑:使用Regex是可能的,这里是操场上的一个版本:https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=c6f69f5018e38677af1624a7bfcd186c。
pub fn validate_password(string: &str) -> bool {
let regex_no_whitespaces = Regex::new(r"^\s*\S+\s*$").unwrap();
let no_whitespaces = regex_no_whitespaces.is_match(&string);
let regex_one_uppercase = Regex::new(r"[a-z]{1,}").unwrap();
let one_uppercase = regex_one_uppercase.is_match(&string);
let regex_one_lowercase = Regex::new(r"[A-Z]{1,}").unwrap();
let one_lowercase = regex_one_lowercase.is_match(&string);
let regex_one_digit = Regex::new(r"[0-9]{1,}").unwrap();
let one_digit = regex_one_digit.is_match(&string);
let regex_length = Regex::new(r".{8,}").unwrap();
let length = regex_length.is_match(&string);
let is_valid = no_whitespaces && one_uppercase && one_lowercase && one_digit && length;
return is_valid;
}但@sirdarius提供的版本要干净得多。
发布于 2022-04-09 15:47:05
这里有一个不使用正则表达式的解决方案。
fn is_password_valid(s: &str) -> bool {
let mut has_whitespace = false;
let mut has_upper = false;
let mut has_lower = false;
let mut has_digit = false;
for c in s.chars() {
has_whitespace |= c.is_whitespace();
has_lower |= c.is_lowercase();
has_upper |= c.is_uppercase();
has_digit |= c.is_digit(10);
}
!has_whitespace && has_upper && has_lower && has_digit && s.len() >= 8
}发布于 2022-11-30 14:10:12
fn is_password_valid(password: &str) -> bool {
let mut has_uppercase = false;
let mut has_lowercase = false;
let mut has_digit = false;
let mut has_whitespace = false;
for c in password.chars() {
if c.is_uppercase() {
has_uppercase = true;
} else if c.is_lowercase() {
has_lowercase = true;
} else if c.is_digit(10) {
has_digit = true;
} else if c.is_whitespace() {
has_whitespace = true;
}
}
has_uppercase && has_lowercase && has_digit && !has_whitespace
}https://stackoverflow.com/questions/71809435
复制相似问题