Regex repeated lines

Viewed 32

Suppose I have this String:

Speaker 1:
Lorem ipsum
Speaker 1:
This is text
Speaker 1:
Another one
Speaker 2:
Yadda Yadda
Speaker 1:
Text
Speaker 2:
New text

I want to to remove the second and third occurence of Speaker 1: but keep the first and fourth one via regex. I tried using (Speaker 1:)(.|\n)*((Speaker 1:))(.|\n)*(Speaker 2:) to be able to access the groups but this didn't work out. How can I access only the repeated lines containing Speaker 1: which are followed by Speaker 2:?

1 Answers

You might use a capture group to keep the first occurrence.

Then match all consecutive parts that start with the same Speaker , digits and : using a backreference.

In the replacement use group 1 to keep the first occurrence.

^((Speaker \d+:)(?:\n(?!Speaker ).*)*)(?:\n\2(?:\n(?!Speaker ).*)*)*
  • ^ Start of string
  • ( Capture group 1
    • (Speaker \d+:) Capture group 2 Match Speaker and 1+ digits
    • (?:\n(?!Speaker ).*)* Match all lines that do not start with Speaker
  • ) Close group 1
  • (?: Non capture group
    • \n\2 Match a newline and a backreference to group 1
    • (?:\n(?!Speaker ).*)* Match a newline and all lines that do not start with Speaker
  • )* Close the non capture group and optionally repeat it

Regex demo

Related