Java模式与组匹配

问题描述 投票:0回答:1

当我运行此代码时,它只打印出每行匹配的第一个模式中找到的组。但是,我想在每行中替换多个字符串,并且我希望它在匹配的模式中打印出每个字符串的特定组。如何更改它以便打印出特定于每行中找到的模式/字符串的组,而不是仅打印第一个模式中匹配的组?

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);
            }
        }
    }
}
java regex pattern-matching regex-group
1个回答
1
投票

你误解了Matcherfind()replaceAll()函数的目的。在replaceAll()循环中使用find()是没有意义的:

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之间的区别,因为我怀疑你的正则表达式中的量词可能需要从+变为+?++。但由于我不知道您的输入或预期输出是什么样的,我只能猜测这一部分。

我上面提到的问题很重要。

祝好运。

© www.soinside.com 2019 - 2024. All rights reserved.