Backreference across lines: duplicate lines
A regex exercise from Regexdrill. Solve it with a pattern box with live highlighting in your browser, checked against hidden test strings, and it is checked the moment you submit.
The task
Each test is a block of several lines. Whenever a line is immediately repeated, keep one copy and remove every repeat that follows it. Lines are never empty. The anchors need to work per line, so use the m flag, and every run of repeats must be handled.
What this exercise teaches
^(.+)(?:\n\1)+$ with the gm flags and the replacement $1 matches a line plus every identical line right after it, and writes the line back once. Without the anchors, a short line like b could match the tail of ab.
A hint if you get stuck
Capture a whole line between ^ and $, then require a line break followed by \1, repeated one or more times. With the g and m flags this runs on every line of the block.
Try it now, free, no account needed
Every exercise on Regexdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. A free account adds the worked solution; Pro adds timed mode and the certificate.
Open this exerciseMore exercises in Advanced
- Lookahead: amounts before USDFree
- Negative lookahead: not starting with unFree
- Lookbehind: amounts after $Free
- Negative lookbehind: positive numbers onlyFree
- Lazy vs greedy: the first quoted textFree
- Named groups: year, month, dayFree
- Password rules with lookaheadsFree
- Word boundaries: replace a whole wordFree
- Unicode letters with the u flagFree
- Multiline flag: TODO linesFree
- Multiline: trailing whitespace on every lineFree
- Named groups in a replacementFree
- Multiline anchors: lines ending in a semicolonFree
- Negative lookahead: numbers that are not percentagesFree