[英]Java Pattern Matching with Groups
當我運行此代碼時,它僅打印出在每行匹配的第一個模式中找到的組。 但是,我想在每行中替換多個字符串,並且我希望它為匹配模式中的每個字符串打印出特定的組。 如何更改它,以便打印出特定於每行中找到的模式/字符串的組,而不是僅打印找到的第一個匹配模式中的組?
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 : appendTail(sb)
您可能還想看看這個問題,關於貪婪量詞 , 不情願量詞和占有量詞之間的區別,因為我懷疑您的正則表達式中的量詞可能需要從+
更改為+?
或++
。 但是由於我不知道您的輸入或期望的輸出是什么樣子,所以我只能猜測這部分。
我上面提到的問題是一個大問題。
祝好運。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.