Matching everything except beginning duplicate letters

Viewed 45

I'm trying to match words but without the first or all duplicate letters at the beginning Ex:

AADBE -> match: DBE

AAADKER -> match: DKER

DDDDDDKER -> match: KER

ADEDE -> match: DEDE

I tried to use look-behind but for some reason the prioritization doesn't work correctly and it's quite far of:

/(?<=\s(\2([A-Z])|[A-Z]))[A-Z]+/

There's probably a much easier way to do this.

2 Answers

You can use 2 capture groups, and the value is in capture group 2.

\b([A-Z])\1*([A-Z]+)\b

The pattern matches:

  • \b A word boundary to prevent a partial match
  • ([A-Z])\1* Capture group 1, match a single char A-Z and optionally repeat the char that is captured in group 1 using a backreference \1
  • ([A-Z]+) Capture group 2, repeat 1+ times a char A-Z
  • \b A word boundary

Regex demo

Replace

^([A-Z])\1*

with an empty string.

See regex proof.

EXPLANATION

--------------------------------------------------------------------------------
  ^                        the beginning of the string
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    [A-Z]                    any character of: 'A' to 'Z'
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  \1*                      what was matched by capture \1 (0 or more
                           times (matching the most amount possible))
Related