Search code examples
regexregex-group

Regex: why is numeric capturing after negative lookahead not working?


(.)(?!\1)\1

I think this should match any character [c], followed by any character that is not [c], then followed by [c] again.

like 'aba', 'xyx'

But online regexr validator is telling me im wrong. Where is the issue?

Thanks in advance.enter image description here


Solution

  • You were correctly checking if the second character isn't the same as the first (group), but you forgot to allow a match on the second character otherwise.

    (.)(?!\1).\1

    https://regex101.com/r/vvapcB/1


    If you want to also want the matches to be 3 characters only,

    (?=.{3}$)(.)(?!\1).\1

    https://regex101.com/r/2IVxNK/1