编译正则表达式
String re = "\d+";
Pattern compile = Pattern.compile(re);
Matcher matcher = compile.matcher("123123123213");
提取字符串
// 一个括号内会被分为一个group
String re = "(\\d{2}):(\\d{2}):(\\d{2})";
Pattern compile = Pattern.compile(re);
Matcher matcher = compile.matcher("24:12:64我是不匹配99:12:22");
while (matcher.find()) {
System.out.println("----------------");
for (int i = 0; i <= matcher.groupCount(); i++) {
System.out.println(i + "\t:\t" + matcher.group(i));
}
}
输出
----------------
0 : 24:12:64
1 : 24
2 : 12
3 : 64
----------------
0 : 99:12:22
1 : 99
2 : 12
3 : 22
Process finished with exit code 0
matcher是一次匹配整个句子,find是尝试匹配句子中的子字符串
// matcher
String re = "((\\d{2}):(\\d{2}):(\\d{2}))";
Pattern compile = Pattern.compile(re);
Matcher matcher = compile.matcher("24:12:64sjdfksjdkfj99:12:22");
while (matcher.find()) {
System.out.println("----------------");
for (int i = 0; i <= matcher.groupCount(); i++) {
System.out.println(i + "\t:\t" + matcher.group(i));
}
}
// find
String re = "(\\d{2}):(\\d{2}):(\\d{2})";
Pattern compile = Pattern.compile(re);
Matcher matcher = compile.matcher("24:12:64");
if (matcher.matches()) {
for (int i = 0; i <= matcher.groupCount(); i++) {
System.out.println(i + "\t:\t" + matcher.group(i));
}
}
原文:https://www.cnblogs.com/xiaojiluben/p/14825416.html