Sushil
Sushil

Reputation: 390

pcre regex for removing adjacent duplicates

Given a string having duplicate characters, what would be the proper regex to remove adjacent duplicates? I am unable to figure out how to use backreference to write final output. For eg. input: "1111112222223333344444111"; output: "12341"

Upvotes: 1

Views: 296

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

you can use this:

pattern: (.)\g{1}+
replacement: $1

or this:

pattern: (.)\K\g{1}+

and nothing for replacement

example with php:

preg_replace('~(.)\K\g{1}+~', '', '1111112222223333344444111');

Upvotes: 1

Related Questions