group查询
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Client {
public static void main(String[] args) {
String content = "java123python456go";
Matcher matcher = Pattern.compile("([a-z]+)([0-9]+)").matcher(content);
while (matcher.find()) {
System.out.println(matcher.group(0) + " " + matcher.group(1) + " " + matcher.group(2));
}
}
}
group(0)表示匹配到的完整字符串,group(1)表示第一个括号中的内容,依次类推。
输出为
java123 java 123
python456 python 456
group替换
import java.util.ArrayDeque;
import java.util.Deque;
import java.util.function.Function;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Client2 {
public static void main(String[] args) {
String content = "java123python456go";
String regex = "([a-z]+)([0-9]+)";
System.out.println(replaceOfMatchGroup(content, regex, 1, word -> word.toUpperCase()));
System.out.println(replaceOfMatchGroup(content, regex, 1, word -> word + "good"));
}
public static String replaceOfMatchGroup(String sourceString, String pattern,
int groupToReplace, Function<String, String> replaceStrategy) {
//模拟栈,保存所有group的起始和结束位置
Deque<Integer> startPositions = new ArrayDeque<>();
Deque<Integer> endPositions = new ArrayDeque<>();
Matcher matcher = Pattern.compile(pattern).matcher(sourceString);
while (matcher.find()) {
startPositions.addLast(matcher.start(groupToReplace));
endPositions.addLast(matcher.end(groupToReplace));
}
StringBuilder sb = new StringBuilder(sourceString);
while (!startPositions.isEmpty()) {
int start = startPositions.removeLast();
int end = endPositions.removeLast();
if (start >= 0 && end >= 0) {
//在区间[start,end)中使用replaceStrategy策略替换
sb.replace(start, end, replaceStrategy.apply(sourceString.substring(start, end)));
}
}
return sb.toString();
}
}
输出为
JAVA123PYTHON456go
javagood123pythongood456go
Matcher类中只有replaceAll()和replaceFirst()方法,只能替换完整的匹配字符串,这里实现一个可以替换任意group的方法。
参考
java Matcher中的group
Java Pattern和Matcher用法
Can I replace groups in Java regex?