编译正则表达式
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 + " : " + 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是一次匹配整个句子,find是尝试匹配句子中的子字符串
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class scratch_1 {
public static void main(String[] args) {
/**
* 输出
* ----------------
* 0 : 24:12:64
* 1 : 24:12:64
* 2 : 24
* 3 : 12
* 4 : 64
* ----------------
* 0 : 99:12:22
* 1 : 99:12:22
* 2 : 99
* 3 : 12
* 4 : 22
*/
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 + " : " + matcher.group(i));
}
}
// find
/**
* 输出为空,因为后面有别的单词,不完全匹配
* 如果替换输入字符串为24:12:64,输出
* 0 : 24:12:64
* 1 : 24
* 2 : 12
* 3 : 64
*/
String re1 = "(\d{2}):(\d{2}):(\d{2})";
Pattern compile1 = Pattern.compile(re1);
Matcher matcher1 = compile1.matcher("24:12:64我是不匹配99:12:22");
if (matcher1.matches()) {
for (int i = 0; i <= matcher1.groupCount(); i++) {
System.out.println(i + " : " + matcher1.group(i));
}
}
}
}