public class MainUtil {
public static void main(String[] args) {
refGroup();
}
// split 高级用法,保留分隔词
// 使用场景: 需要对分隔符做对应解析
static void splitWith(){
String rawStr = "1,2,3";
Arrays.asList(rawStr.split("(?=,)")).forEach(System.out::println);
}
// group 跨越分组
// 使用场景: 正则需要使用分组的|功能,但是又不希望计入分组计数
static void groupOver(){
String rawStr = "abc123ab123";
Pattern pattern=Pattern.compile("[a-z]+[0-5]+(?:ab|cd)?([0-9]+)");
Matcher matcher = pattern.matcher(rawStr);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
}
//正则匹配并替换
// 使用场景: 一帮用于变量替换
static void regexReplace(){
String rawStr = "____${a}--${b}____";
Pattern pattern = Pattern.compile("\\$\\{(\\w+)\\}");
Matcher matcher = pattern.matcher(rawStr);
StringBuffer sb = new StringBuffer();
while (matcher.find()){
matcher.appendReplacement(sb,matcher.group(1).toUpperCase());
}
matcher.appendTail(sb);
System.out.println(sb.toString());
}
//分组引用
static void refGroup(){
String rawStr = "abc123tttabc";
Pattern pattern = Pattern.compile("([a-z]+)\\d+[a-z]+?\\1");
System.out.println(pattern.matcher(rawStr).matches());
System.out.println(rawStr.replaceAll("\\d+","_$0_"));
}
}
网友评论