(1) String
public boolean
matches
(String regex)
public String
replaceAll
(String regex, String replacement)
public String
replaceFirst
(String regex, String replacement)
public String[]
split
(String regex)
(2) Pattern
public static Pattern
compile
(String regex)
public static boolean
matches
(String regex, CharSequence input)
典型的调用顺序是
Pattern p = Pattern.
compile
("a*b");
Matcher m = p.
matcher
("aaaaab");
boolean b = m.
matches
();
在仅使用一次正则表达式时
boolean b = Pattern.matches("a*b", "aaaaab");
java 示例
1 /**
2 * @title 密码验证,规则:长度8~30,不能含有#和空格,至少含有数字、大写、小写、特殊字符中的3种
3 * @param password
4 * @return boolean
5 */
6 private static boolean validatePassword(String password) {
7 if (StringUtils.isBlank(password)) {
8 return false;
10 // 长度8~30
11 if (password.length() < 8 || password.length() > 30) {
12 return false;
13 }
14 // 不能含有#和空格
15 if (password.contains("#") || password.contains(" ")) {
16 return false;
17 }
18 int typecount = 0;
19 // 如果含有数字
20 if (Pattern.matches(".*[0-9]+.*", password)) {
21 typecount++;
22 }
23 // 如果含有大写字母
24 if (Pattern.matches(".*[A-Z]+.*", password)) {
25 typecount++;
26 }
27 // 如果含有小写字母
28 if (Pattern.matches(".*[a-z]+.*", password)) {
29 typecount++;
30 }
31 // 如果含有特殊字符
32 if (Pattern.matches(".*[^A-Za-z0-9]+.*", password)) {
33 typecount++;
34 }
35 // 至少含有数字、大写、小写、特殊字符中的3种
36 if (typecount < 3) {
37 return false;
38 }
39 return true;