8

I want to match patterns of alternating lowercase characters.

ababababa -> match

I tried this

([a-z][a-z])+[a-z]

but this would be a match too

ababxyaba
cmplx96
  • 1,541
  • 8
  • 34
  • 48

1 Answers1

15

You can use this regex with 2 back-reference to match alternating lowercase letters:

^([a-z])(?!\1)([a-z])(?:\1\2)*\1?$

RegEx Demo

RegEx Breakup:

  • ^: Start
  • ([a-z]): Match first letter in capturing group #1
  • (?!\1): Lookahead to make sure we don't match same letter again
  • ([a-z]): Match second letter in capturing group #3
  • (?:\1\2)*: Match zero or more pairs of first and second letter
  • \1?: Match optional first letter before end
  • $: End
anubhava
  • 761,203
  • 64
  • 569
  • 643