MySQL REGEXP - Removing white space and non-numeric characters

前端 未结 4 1454
谎友^
谎友^ 2021-01-06 03:36

I want to do a search in a MySQL database for phone numbers.

At present with this query:

SELECT person FROM people WHERE phone_number RLIKE \'1234567         


        
4条回答
  •  时光说笑
    2021-01-06 04:14

    I can think of two ways to do it, neither as elegant as I'd hoped though.

    First: Use regex in RLIKE to allow spaces and brackets everywhere:

    SELECT person 
     FROM people
     WHERE phone_number RLIKE '[() ]*1[() ]*2[() ]*3[() ]*4[() ]*5[() ]*6[() ]*7[() ]*8[() ]*9'
    

    It basically says there can be brackets and spaces in between each number. It's a bit awkward to make the string though. If you are calling mySQL from another language (say php) you could use the other language to turn '123456789' into 'x1x2x3x4x5x6x7x8x9' where 'x' is [() ]*.

    Second: use mysql REPLACE to remove spaces and brackets before doing comparison:

    SELECT person 
     FROM people
     WHERE REPLACE(REPLACE(REPLACE(phone_number,' ',''),'(',''),')','') = '123456789';
    

    This successively replaces spaces, open brackets, and closing brackets in phone_number with ''.

    I think I prefer this second method. To remove all spaces you just need REPLACE(phone_number,' ','') and to remove all () you need two REPLACE.

    I suppose the first is more flexible with respect to adding extra characters though. It's a shame MySQL doesn't have a regex-enabled REPLACE!

提交回复
热议问题