Regex Backreference Repeated Word

Match a repeated word with a backreference: \1 re-captures group one inside the pattern and $1 reuses it in replaceAll to collapse duplicates.

JavaForm Validation

Code

snippet
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);
    }
}

How the snippet works

Regex Backreference Repeated Word reduces to the class DuplicateWordFinder and the function main.

Repetition is confined to while (m.find()) — the rest of the file is straight-line.

Applying it

Output lines are prefixed (duplicate: \, fixed:), making each step’s effect easy to spot.

Statements that matter

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");

Interactive Tools for This Topic

FAQ

What does Regex Backreference Repeated Word print when run?
The script runs standalone; its 2 labeled outputs include `duplicate: \`, `fixed:`.