1. String.replaceAll(String regex, String replacement) 方法问题
默认替换会把regex字符串当作一个正则表达式解析,这样的话如果想直接替换就不能出现正则语义。否则会出错
Exception in thread "main" java.util.regex.PatternSyntaxException: Dangling meta character '+' near index 18
// 测试案例
"abc+++cba".replaceAll("+++","sss")
// 解决方案
"abc+++cba".replaceAll("\\+\\+\\+","sss");
org.apache.commons.lang3.StringUtils.replace("abc+++cba","+++","sss");
java.util.regex.Matcher#find() 与 java.util.regex.Matcher#matches() 比较
- matches 方法是字符完全满足正则;
- find 方法是字符串存在一个或多个字串满足正则,调用了find后会移动定位,假设只有一个字串满足的话,再此调用会放回 false,所以又是需要同
java.util.regex.Matcher#reset()
组合使用;
Pattern pattern = Pattern.compile("正则字符串");
Matcher matcher = pattern.matcher("待匹配字符串");
System.out.println(matcher.matches());
if (matcher.find()) {
matcher.reset();
while (matcher.find()) {
System.out.println(matcher.group(1));
}
}else{
System.out.println("正则没匹配上啊");
}
标签:regex,java,matcher,正则,Matcher,find
From: https://www.cnblogs.com/listjiang/p/17124215.html