← 中文资源

简体中文版本

正则反向引用找重复词

反向引用 \1 让模式匹配与第 1 组相同的文本:find 逐个定位重复单词的位置,replaceAll 再用 $1 把重复折叠成单次出现。

阅读英文原文

实现说明

全部逻辑都在类 DuplicateWordFinder和函数 main中。 while (m.find()) 反复执行,循环体之外没有别的重复。

使用要点

  • 直接运行文件,输出会带上标签,比如 duplicate: \、fixed:——输出的每一行都能指回产生它的那次调用。

常见问题

运行「正则反向引用找重复词」会打印什么?

文件本身就是完整程序,直接运行——输出行带有 duplicate: \、fixed: 这类标签。

核心语句

Pattern repeated = Pattern.compile("\\b(\\w+)\\s+\\1\\b", Pattern.CASE_INSENSITIVE);
Matcher m = repeated.matcher("please review review the draft today today");
String fixed = repeated.matcher("say hello hello loudly").replaceAll("$1");

代码示例

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DuplicateWordFinder {

    public static void main(String[] args) {
        // backreference \1:匹配与第 1 组捕获完全相同的词(重复单词)
        Pattern repeated = Pattern.compile("\\b(\\w+)\\s+\\1\\b", Pattern.CASE_INSENSITIVE);
        Matcher m = repeated.matcher("please review review the draft today today");

        while (m.find()) {
            System.out.println("duplicate: \"" + m.group(1) + "\" at index " + m.start());
        }

        // 替换里用 $1 引用第 1 组:把重复折叠成单次出现
        String fixed = repeated.matcher("say hello hello loudly").replaceAll("$1");
        System.out.println("fixed: " + fixed);
    }
}