Regexdrill

Level 5: Advanced Exercise 66 of 70 Free

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 exercise

More exercises in Advanced