【发布时间】:2023-03-08 10:17:01
【问题描述】:
目前,此代码在找到匹配的每一行之后将模式匹配附加到字符串缓冲区。但是,我想进行模式匹配并替换 2 个不同的模式,并且程序打印出找到这两种模式的行的副本,因为它附加了找到模式匹配的每一行。有什么方法可以打印出替换的最后一行?我想我可能必须在第一个模式匹配器中将附加更改为替换,但我不知道有什么方法可以做到这一点。
public static void main(String[] args) throws FileNotFoundException {
RealReadFile file = new RealReadFile();
while (!file.endOfFile()) {
String line = file.nextLine();
Pattern cpochhammer = Pattern.compile("(\\(([^)]+)\\)_\\{([^}]+)\\})");
Matcher pochhammer = cpochhammer.matcher(line);
StringBuffer rplcmntBfr = new StringBuffer();
while(pochhammer.find()) {
pochhammer.appendReplacement(rplcmntBfr, "\\\\pochhammer{$2}{$3}");
}
pochhammer.appendTail(rplcmntBfr);
Pattern npochhammer = Pattern.compile("(\\(([^)]+)\\)_(.))");
Matcher ppochhammer = npochhammer.matcher(rplcmntBfr);
while(ppochhammer.find()) {
ppochhammer.appendReplacement(rplcmntBfr, "\\\\pochhammer{$2}{$3}");
}
//ppochhammer.appendTail(rplcmntBfr);
System.out.println(rplcmntBfr);
}
}
【问题讨论】: