最近有一个简单的字符串验证的任务,发现写代码这些年都没养成记录和分享的习惯,那就开blog行动吧!!!
我的任务很简单验证字符串只由数字、字母和某几个字符组成。
由浅入深上代码。
下面的代码判断字符串里面是否带有任意个(1个或多个) ! or @ :
import ;
import ;
public class StringUtil {
public static void main(String[] args) {
String input = "hello!@world";
//中括号:表示里面的任意字符可选, 加号:代表1个或多个
String pattern = "[!@]+";
Pattern p = (pattern);
Matcher m = (input);
if (()) {
("input 包含 ! or @");
} else {
("input 不包含 ! or @");
}
}
}
下面的代码判断字符串是否只由 ! or @ 组成
import ;
import ;
public class PatternUtil {
public static void main(String[] args) {
String input = "!!!!!!!!@@@";
//^: 表示字符串开始, $: 表示行结束
//中括号:表示里面的任意字符可选, 加号:代表1个或多个
String pattern = "^[!@]+$";
Pattern p = (pattern);
Matcher m = (input);
if (()) {
("input 只有 ! 和 @");
} else {
("input 包含 ! 和 @ 以外的字符");
}
}
}
我的最终目标:验证字符串只由数字、字母和 "~!@#$%&*()-_+" 这些特殊符号组成
import ;
import ;
public class PatternUtil {
public static void main(String[] args) {
String input = "hello world";
//^: 表示字符串开始, $: 表示行结束
//中括号:表示里面的任意字符可选, 加号:代表1个或多个
//a-z: 表示小写字符, A-Z: 表示大写字符, 0-9: 表示数字
String pattern = "^[a-zA-Z0-9~!@#$%&*()-_+ ]+$";
Pattern p = (pattern);
Matcher m = (input);
if (()) {
("input 验校成功");
} else {
("input 验校失败");
}
}
}
验校密码格式(至少包含一个数字,至少包含一个字母,至少包含一个特殊符号,长度至少为8个字符)
import ;
import ;
public class PasswordValidator {
public static final String PASSWORD_PATTERN = "^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[~!@#$%^&*()_+:;,.?]).{8,}$";
public static boolean isValidPassword(final String password) {
Pattern pattern = (PASSWORD_PATTERN);
Matcher matcher = (password);
return ();
}
public static void main(String[] args) {
(isValidPassword("Abc1234#")); // true
(isValidPassword("password")); // false
}
}
上面的正则表达式使用了一些特殊的元字符来保证密码同时包含数字、字母和特殊符号。具体地:
^:匹配字符串的开头
(?=.*[0-9]):密码中至少包含一个数字
(?=.*[a-zA-Z]):密码中至少包含一个字母
(?=.*[~!@#$%^&*()_+:;,.?]):密码中至少包含一个特殊符号
.{8,}:密码长度至少为8个字符
$:匹配字符串的结尾
请注意:模式中的特殊字符 "~!@#$%^&*()_+:;,.?" 可能根据密码验证要求有所不同。