1.Java验证用户名的正则表达式
- @Test
- public void formalRegex() {
- String str = "123+123";
-
- Pattern pattern = Pattern.compile("[0-9a-zA-Zu4E00-u9FA5]+");
- Matcher matcher = pattern.matcher(str);
-
- if (!matcher.matches() ) {
- System.out.println("不满足条件");
- } else {
- System.out.println("满足正则式");
- }
- }
这是一般的用户名验证,这种验证是要求用户名不能有空格的今天遇到了比较麻烦的问题,用户名允许有空格......在允许有空格的情况下要注意把"
"等特殊的字符给过滤掉,于是采用下面的代码
- @Test
- public void spaceRegex() {
- String str = "123
123";
-
- Pattern pattern = Pattern.compile("[0-9a-zA-Zu4E00-u9FA5\s]+");
- Matcher matcher = pattern.matcher(str);
-
- Pattern special = Pattern.compile("\s*| |
|
");
- Matcher specialMachter = special.matcher(str);
-
- if (!matcher.matches() || !specialMachter.matches()) {
- System.out.println("不满足条件");
- } else {
- System.out.println("满足正则式");
- }
- }
使用两遍正则验证,换行制表等特殊字符就被过滤掉了