Capture group stops working when there are newlines, despite s modifier

Viewed 31

I have a LaTeX source file with content that looks like this:

\textcolor{red}{This {is} a test}

and my goal is to remove the color modifiers but keep all the content inside, i.e.,

This {is} a test

I could achieve this with the following regex (perl) for most cases s/\\textcolor{red}{([^{}]*+(?:{(?1)}[^{}]*)*+)}/$1/sg. Here is the example:

echo -e '\\textcolor{red}{This {is} a test}' | perl -pe 's/\\textcolor{red}{([^{}]*+(?:{(?1)}[^{}]*)*+)}/$1/sg'

Results in This {is} a test as expected. But when I add a linebreak in the matching group, it stops working. For example:

echo -e '\\textcolor{red}{This \n {is} a test}' | perl -pe 's/\\textcolor{red}{([^{}]*+(?:{(?1)}[^{}]*)*+)}/$1/sg'

Results in

\textcolor{red}{This 
 {is} a test}

Despite using the s modifier.

What part of this RegEx is producing the wrong results due to the newline? It seems like the fact that the "main" closing bracket is in a new line is preventing the string to match, but I can't see why the linebreak would behave differently than any other character here.

0 Answers
Related