当我运行此代码时,它仅打印在每行匹配的第一个模式中找到的组。但是,我想在每一行中替换多个字符串,并且我希望它打印出它匹配的模式中每个字符串的特定组。如何更改它,以便它打印出特定于在每行中找到的模式/字符串的组,而不是仅打印它找到的第一个模式匹配中的组?
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.io.FileNotFoundException;
import java.io.File;
public class RealReadFile {
private static final String fileName = "KLSadd.tex";
private Scanner myFile = null;
// No-args constructor, create a new scanner for the specific file defined
// above
public RealReadFile() throws FileNotFoundException {
if (myFile == null)
myFile = new Scanner(new File(fileName));
}
// One-arg constructor - the name of the file to open
public RealReadFile(String name) throws FileNotFoundException {
if (myFile != null)
myFile.close();
myFile = new Scanner(new File(name));
}
public boolean endOfFile() { // Return true is there is no more input
return !myFile.hasNext(); // hasNext() returns true if there is more input, so I negate it
}
public String nextLine() {
return myFile.nextLine().trim();
}
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);
while (pochhammer.find()){
System.out.println(line);
String line2=pochhammer.replaceAll("\\\\pochhammer{" + pochhammer.group(2) + "}{" + pochhammer.group(3) + "}");
System.out.println(line2);
}
}
}
}
最佳答案
您误解了 Matcher
的 find()
和 replaceAll()
函数的用途。在 find()
循环中使用 replaceAll()
是没有意义的:
while (pochhammer.find()){
System.out.println(line);
String line2=pochhammer.replaceAll("\\\\pochhammer{" + pochhammer.group(2) + "}{" + pochhammer.group(3) + "}");
System.out.println(line2);
}
要替换所有实例,您需要将其更改为如下所示:
StringBuffer rplcmntBfr = new StringBuffer();
while(pochhammer.find()) {
pochhammer.appendReplacement(rplcmntBfr, "\\\\pochhammer{" + pochhammer.group(2) + "}{" + pochhammer.group(3) + "}");
}
pochhammer.appendTail(rplcmntBfr);
System.out.println(rplcmntBfr);
使用replaceAll(s)
访问各个匹配组和
pochhammer.replaceAll("\\\\pochhammer{" + pochhammer.group(2) + "}{" + pochhammer.group(3) + "}");
没有意义,因为group(i)
只能与find()
一起使用,而replaceAll(s)
用于替换同时匹配该行中的所有内容。
这里有一个关于使用 find()
、appendReplacement(sb,s)
和 appendTail(sb)
进行替换的教程:http://tutorials.jenkov.com/java-regex/matcher.html#appendreplacement-appendtail-methods
您可能还想看看这个问题,了解 Greedy vs. Reluctant vs. Possessive Quantifiers 之间的区别,因为我怀疑正则表达式中的量词可能需要从 +
更改为 +?
或 ++
。但由于我不知道你的输入或预期输出是什么样的,所以我只能猜测这部分。
我上面提到的问题是个大问题。
祝你好运。
关于Java 模式与组的匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22129439/