Java验证含空格的用户名
Java验证含空格的用户名
1.Java验证用户名的正则表达式
- @Test
- public void formalRegex() {
- String str = "123+123";
- Pattern pattern = Pattern.compile("[0-9a-zA-Z\u4E00-\u9FA5]+");
- Matcher matcher = pattern.matcher(str);
- if (!matcher.matches() ) {
- System.out.println("不满足条件");
- } else {
- System.out.println("满足正则式");
- }
- }
今天遇到了比较麻烦的问题,用户名允许有空格......
在允许有空格的情况下要注意把"\n"等特殊的字符给过滤掉,于是采用下面的代码
- @Test
- public void spaceRegex() {
- String str = "123\n 123";
- Pattern pattern = Pattern.compile("[0-9a-zA-Z\u4E00-\u9FA5\\s]+");
- Matcher matcher = pattern.matcher(str);
- Pattern special = Pattern.compile("\\s*|\t|\r|\n");
- Matcher specialMachter = special.matcher(str);
- if (!matcher.matches() || !specialMachter.matches()) {
- System.out.println("不满足条件");
- } else {
- System.out.println("满足正则式");
- }
- }
评论暂时关闭