Search code examples
phpmysqlpreg-match

Regular expression to match identical repeated digits in phone numbers


Sorry if the title wasnt descriptive enough. I have a bunch of phone numbers in a mysql database. Dont know if there is a query to do this or better to use something like preg_match with PHP. But I need to search using a pattern like so:

Ends with XXXX or Contains 4XXX

The X means the same number. So if I searched for Ends with XXXX Im looking for any number like so:

671-0000

421-5555

789-1111

If I search Contains 4XXX then Im looking for any number like so:

345-4111

156-4777

For some reason I cant wrap my brain around this. Seems like it would be pretty easy. Can anyone help? Appreciate it!


Solution

  • The simplest expression here for the NXXX pattern is:

    \d(\d)\1{2}
    

    If the regular expression engine you're using supports that kind of back-tracking with \1, which references whatever digit happens to be in the (\d) spot, then this should work as in this example.

    You could also adapt that for the XXXX pattern like:

    (\d)\1{3}
    

    Where that's three repeated, identical digits after the first.