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.
Code
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
JSON to Zod Schema ConverterInfer typed Zod z.object schemas from JSON payloads locally, supporting nested objects, merged array shapes, enums, nullable fields, and JSDoc comments.Regex Backreference ExplainerScan a regular expression to list its capturing groups, named groups, non-capturing groups, and backreferences, with warnings for dangling references.JSON Schema ValidatorValidate JSON data against a JSON Schema definition and get detailed error reports. Supports type checking, required fields, and common constraint validation.JSONL / NDJSON InspectorValidate NDJSON and JSON Lines line-by-line, pinpoint syntax errors by line number, analyze key frequencies and types, and export a pretty JSON array.
FAQ
- What does Regex Backreference Repeated Word print when run?
- The script runs standalone; its 2 labeled outputs include `duplicate: \`, `fixed:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.