一、Java中使用Pattern类进行正则匹配
@org.junit.Test
public void test1() {
String regex = "^[\\s]*abc[\\s]";
String target = " abc ";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(target);
boolean flag = matcher.matches();
if (flag) {
System.out.println("匹配成功");
} else {
System.out.println("匹配失败");
}
}
说明:1、注意导入junit包。2、注意转义 3、regex = "^[\\s]*abc[\\s]" 表示匹配以多个空字符开头,一个空字符结尾。
二、正则表达式()分组的使用
@org.junit.Test
public void test2() {
String regex = "hot(\\d)s(\\d*)";
String target = "hot5s15";
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(target);
boolean flag = matcher.matches();
if (flag) {
for (int i = matcher.groupCount(); i >= 1; i--) {
String groupi = matcher.group(i);
System.out.println("i:" + i + " groupi:" + groupi);
}
System.out.println("匹配成功");
} else {
System.out.println("匹配失败");
}
}