这篇文章主要记录怎样使用java api中的java.util.regex.
Matcher 和java.util.regex.
Pattern例如,用户名的正则表达式如下:
上述正则表达式的含义:
- ^ # Start of the line
-
[a-z0-9_-] # Match characters and symbols in the list, a-z, 0-9, underscore, hyphen
-
{3,15} # Length at least 3 characters and maximum length of 15
-
$ # End of the line
完整实例:
- package org.hello.reg;
-
-
import java.util.regex.Matcher;
-
import java.util.regex.Pattern;
-
-
public class UsernameValidator {
-
-
private Pattern pattern;
-
private Matcher matcher;
-
-
public static void main(String[] args){
-
UsernameValidator usernameValidator = new UsernameValidator();
-
String[] usernames = new String[6];
-
usernames[0] = "hello";
-
usernames[1] ="he#llo";
-
usernames[2] = "he";
-
usernames[3] = "ho_o";
-
usernames[4] = "kkkkkkkkkkkkkkkkkkkk";
-
usernames[5] = "#####";
-
-
for(String name : usernames){
-
boolean valid = usernameValidator.validate(name);
-
System.out.println("Username is valid: " + name + " , " + valid);
-
}
-
-
}
-
-
private static final String USERNAME_PATTERN = "^[a-z0-9_-]{3,15}$";
-
-
public UsernameValidator(){
-
pattern = Pattern.compile(USERNAME_PATTERN);
-
-
}
-
-
public boolean validate(final String username){
-
matcher = pattern.matcher(username);
-
return matcher.matches();
-
}
-
}
运行结果:
- Username is valid: hello , true
-
Username is valid: he#llo , false
-
Username is valid: he , false
-
Username is valid: ho_o , true
-
Username is valid: kkkkkkkkkkkkkkkkkkkk , false
-
Username is valid: ##### , false
阅读(9915) | 评论(0) | 转发(0) |