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
3
  • "Alternating" or just "uneven number" of chars? If the latter, enclose the pattern with ^ and $ anchors. Aug 4, 2017 at 10:28
  • what do you mean by alternating lowercase characters ?
    – marvel308
    Aug 4, 2017 at 10:31
  • a string containing an alternation of two of the same characters - > xyxyxyxy but not xyxyxyabxyxy
    – cmplx96
    Aug 4, 2017 at 10:37

1 Answer 1

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
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.