當我運行此代碼時,它僅打印出每行匹配的第一個模式中找到的組。但是,我想在每行中替換多個字符串,並且希望它爲匹配的模式中的每個字符串打印出特定的組。我怎樣才能改變它,以便它打印出特定於它在每行中找到的模式/字符串的組,而不是隻打印找到的第一個模式匹配的組?與組匹配的Java模式
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);
}
}
}
}
謝謝,但這並不意味着它不會嘗試匹配其餘行?我需要匹配並替換該行的其餘部分。 – user2825125
我意識到一些我以前沒有解決的問題。我已經更新了我的答案。 – aliteralmind
您的正則表達式與'findAll'和'find()'問題相比是次要的。我從我的答案中消除了正則表達式部分。 – aliteralmind