Regex - alternating character matching pattern

I want to match patterns of alternating lowercase characters.

ababababa -> match 

I tried this

 ([az][az])+[az] 

but it will also be a match

 ababxyaba 
+5
source share
1 answer

You can use this regex with 2 backlinks to match alternating lowercase letters:

 ^([az])(?!\1)([az])(?:\1\2)*\1?$ 

RegEx Demo

RegEx Distribution:

  • ^ : Start
  • ([az]) : match the first letter in capture group # 1
  • (?!\1) : Lookahead to make sure we don't repeat the same letter.
  • ([az]) : match the second letter in capture group # 3
  • (?:\1\2)* : match zero or more pairs of the first and second letters
  • \1? : Match the optional first letter to the end
  • $ : End
+10
source

Source: https://habr.com/ru/post/1270579/


All Articles