Vikash Yadav
Vikash Yadav

Reputation: 803

How to find alternating repetitive digit pair?

121426 <- Here, 1 is an alternating repetitive digit.

523563 <- Here, NO digit is an alternating repetitive digit.

552523 <- Here, both 2 and 5 are alternating repetitive digits.

333567 <- Here, 3 is an alternating repetitive digit.

I found re.findall(r'(?=(\d)\d\1)',P) as the solution in editorial but not able to understand it.

Edit - Not allowed to use if conditions.

Upvotes: 18

Views: 6655

Answers (2)

anubhava
anubhava

Reputation: 785651

You may use this regex using lookaheads:

(\d)(?=\d\1)

RegEx Demo

Explanation:

  • (\d): Match and capture a digit in group #1
  • (?=: Start lookahead
    • \d: Match any digit
    • \1: Back-reference to captured group #1
  • ): End lookahead

Upvotes: 29

Chris_Rands
Chris_Rands

Reputation: 41198

You could do this without a regex using zip() in a list comprehension:

>>> s = '552523'
>>> [a for a, b in zip(s, s[2:]) if a == b]
['5', '2']

Upvotes: 12

Related Questions