Regexp to remove specific number of occurrences of character only

You need to make sure there is no character of your choice both on the left and right using a pair of lookaround, a lookahead and a lookbehind. The general scheme is

(?<!X)X{n}(?!X)

where (?<!X) means no X immediately on the left is allowed, X{n} means n occurrences of X, and (?!X) means no X immediately on the right is allowed.

In this case, use

r'(?<!>)>{2}(?!>)'

See the regex demo.

Leave a Comment