Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching incremental digits in numbers

After googling many days about the issue, finally I am posting this question here and hoping to get it solved by experts here; I am looking for the regex pattern that can match incremental back references. Let me explain:

For number 9422512322, the pattern (\d)\1 will match 22 two times, and I want the pattern (something like (\d)\1+1) that matches 12 (second digit is equal to first digit + 1)

In short the pattern should match all occurrence like 12, 23, 34, 45, 56, etc... There is no replacement, just matches required.

like image 378
Gadara Avatar asked Mar 18 '23 23:03

Gadara


2 Answers

What about something like this?

/01|12|23|34|45|56|67|78|89/

It isn't sexy but it gets the job done.

like image 93
Asaph Avatar answered Mar 23 '23 16:03

Asaph


You can use this regex:

(?:0(?=1)|1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9))+.

This will match:

  • Any 0s which are followed by 1s, or
  • Any 1s which are followed by 2s, or
  • Any 2s which are followed by 3s, ...

Multiple times +, then match the corresponding character ..

Here is a regex demo, and the match is:

12345555567877785
like image 21
Unihedron Avatar answered Mar 23 '23 16:03

Unihedron