【问题标题】:Troubleshooting Java replaceAllJava replaceAll 故障排除
【发布时间】:2023-03-11 22:59:02
【问题描述】:

我正在尝试编写一个方法,该方法接受要找到的输入字符串和输入字符串来替换找到的单词的所有实例并返回所做的替换次数。我正在尝试使用 JAVA 正则表达式中的模式和匹配器。我有一个名为“text.txt”的文本文件,其中包括“这是一个测试这是一个测试这是一个测试”。当我尝试搜索“test”并将其替换为“mess”时,该方法每次都返回 1,并且没有替换任何单词 test。

public int findAndRepV2(String word, String replace) throws FileNotFoundException, IOException 
{
    int cnt = 0; 

    BufferedReader input = new BufferedReader( new FileReader(this.filename));
    Writer fw = new FileWriter("test.txt");
    String line = input.readLine();


    while (line != null)
    {
        Pattern pattern = Pattern.compile(word, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(line);
        while (matcher.find()) {matcher.replaceAll(replace); cnt++;}

        line = input.readLine();
    }
    fw.close();
    return cnt;
}

【问题讨论】:

  • 您想替换文字字符串。为什么要使用正则表达式?另外,replaceAll 不返回替换的数量,那它怎么工作?

标签: java regex replaceall


【解决方案1】:

首先,您需要确保您搜索的文本不会被解释为正则表达式。你应该这样做:

Pattern pattern = Pattern.compile(Pattern.quote(word), Pattern.CASE_INSENSITIVE);

其次,replaceAll 做了这样的事情:

public String replaceAll(String replacement) {
    reset();
    boolean result = find();
    if (result) {
        StringBuffer sb = new StringBuffer();
        do {
            appendReplacement(sb, replacement);
            result = find();
        } while (result);
        appendTail(sb);
        return sb.toString();
    }
    return text.toString();
}

注意它是如何调用find 的,直到它找不到任何东西。这意味着您的循环只会运行一次,因为在第一次调用 replaceAll 之后,匹配器已经找到了所有内容。

您应该改用appendReplacement

StringBuffer buffer = new StringBuffer();
while (matcher.find()) {
    matcher.appendReplacement(buffer, replace);
    cnt++;
}
buffer.append(line.substring(matcher.end()));
// "buffer" contains the string after the replacement

我注意到在您的方法中,您实际上并没有对替换后的字符串做任何事情。如果是这样,只需计算find 返回 true 的次数:

while (matcher.find()) {
    cnt++;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-15
    • 2010-11-30
    • 2021-09-11
    • 2012-02-18
    • 2011-03-07
    相关资源
    最近更新 更多