Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

regex - match pattern of alternating characters

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
like image 452
cmplx96 Avatar asked Aug 04 '17 10:08

cmplx96


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9. (a-z0-9) -- Explicit capture of a-z0-9 .

How do I match a pattern in regex?

Using special characters For example, to match a single "a" followed by zero or more "b" s followed by "c" , you'd use the pattern /ab*c/ : the * after "b" means "0 or more occurrences of the preceding item."

What are pattern matching characters?

Regular expression pattern-matching can be performed with either a single character or a pattern of one or more characters in parentheses, called a character pattern. Metacharacters have special meanings, as described in the following table.


1 Answers

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
like image 88
anubhava Avatar answered Sep 20 '22 13:09

anubhava