Search code examples
mysqlregexlaravel

How to make a REGEX pattern in mysql for 3 or more digits that are in sequence?


I've created a regex pattern to match sequences of digits that can be ascending or descending, like 12345, 123, 321, 6789, 7654, etc. However, I believe this approach may not be the most efficient or professional way to achieve this task.

Could you please provide a simpler regex expression that can match number sequences, whether ascending or descending? This is how I'm currently implementing it in Laravel

'sequential' => function ($query) {
    $query->orWhereRaw('plate_number REGEXP ?', ['\\b(123(4(5)?)?|234(5)?|345|456|567(8(9)?)?|678(9)?|789|987(6(5)?)?|876(5)?|765|654|543(2(1)?)?|432(1)?)\\b']);
},

I've attempted several approaches to create a regex pattern that accurately matches sequences of numbers. However, the regex pattern I've come up with seems unprofessional to me. Could you please verify if it's correct, or suggest a better way to achieve this?That plate ads with numbers like e.g 1234,2345, 5432,98765,... ,etc.


Solution

  • Try:

    ^(?:(?<inc>1(?=2)|2(?=3)|3(?=4)|4(?=5)|5(?=6)|6(?=7)|7(?=8)|8(?=9)){2,}.|(?<dec>9(?=8)|8(?=7)|7(?=6)|6(?=5)|5(?=4)|4(?=3)|3(?=2)|2(?=1)){2,}.)$
    

    See: regex101


    Explanation

    • ^...$: match whole string
    • (?:...|...): match either increasing or decreasing
      • (?<inc>...): increasing is defined as
        • 1(?=2)|...: a number and a lookahead ensuring it is followed by successor
        • {2,}.: get this at least two numbers like this and match a third (which trough lookahead is ensured to be a successor)
      • (?<dec>...: do the same for decreasing