Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex Capturing: repeating two letters

Tags:

regex

php

I'm trying to check if a word have three or more repeating 'two letters pare', But the expressing returns true only if the same letter is repeated. Why?

(([a-z])([^\1]))\1\2{2,} 
    ^      ^     ^ ^  ^
    1      2     3 4  5

1) any letter (captured set \1)
2) any character that is not set 1 (captured set \2)
3) captured \1 again
4) captured \2 again
5) at least twice

words that should return TRUE: asasasassafasf, ereeeerererere, dddddtrtrtrtruuuuuuuu

words that should return FALSE: dddddddd, rrrrrrrrrrlkajf, fffffffssssssytytfffffff

like image 226
Sdgsdg Asgasgf Avatar asked Feb 27 '26 17:02

Sdgsdg Asgasgf


2 Answers

You can solve this using a negative lookahead assertion:

([a-z])((?!\1)[a-z])(?:\1\2){2,}

Test it live on regex101.com.

Explanation:

([a-z])  # Match and capture a single ASCII letter in group 1
(        # Match and capture...
 (?!\1)  # unless it's the same letter as the one captured before
 [a-z]   # a single ASCII letter in group 2
)        # End of group 2
(?:\1\2) # Match those two letters
{2,}     # two or more times
like image 185
Tim Pietzcker Avatar answered Mar 01 '26 05:03

Tim Pietzcker


Based on your short description following regex should work for you:

(([a-z])((?!\2)[a-z]))\1{2}

Regex Demo

  • ([a-z]) - matches letters a to z and capture them in a group
  • \2 - Back reference to group #2
  • (?!\2)[a-z]) - matches letters a to z that is NOT group #2
  • \1{2} 2 instances of back reference #1

OR using relative back reference numbering:

(([a-z])(?!\g{-1})[a-z])\1{2}

In short this regex matches 3 consecutive occurrences of a letter pair of different characters.

like image 20
anubhava Avatar answered Mar 01 '26 07:03

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!