Skip to content
Advertisement

How can I find repeating pairs of characters with a regex?

Trying to use regex to replace any occurrences of any set of two characters which repeat in a string. I would like for such patterns to be replaced with one occurrence of the repeating substring and the number of times it was repeated.

For example, in this string below, I would like:

qwertyabababababababababababa

to become:

qwertyab11a

Similarly,

a a a a a a a a a a

should become:

a 9a

I have tried running code similar to this:

JavaScript

but the above obviously didn’t work, and returned this:

he14.5

Advertisement

Answer

You can use a so-called back-reference (1) to match a repetition of a captured group:

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement