有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java使用SQL REGEXP查找手机号码


我们的数据库可以包含不同格式的手机号码,如:“(731)123-4567”或“731-123 45 67”或“731-12-3-[4567]”等。
此外,我在API中获得的搜索输入可以是任何格式
因此,当我需要在db中找到一个使用mobile的用户时,我会清理输入号码,使其看起来像“7311234567”,然后用regexp '(\\+|\\-|\\(|\\)|\\[|\\]| )*'包装/填充它,例如,SQL看起来像这样:

select * from contact where mobile REGEXP '(\\+|\\-|\\(|\\)|\\[|\\]| )*
             1(\\+|\\-|\\(|\\)|\\[|\\]| )*7(\\+|\\-|\\(|\\)|\\[|\\]| )*
             3(\\+|\\-|\\(|\\)|\\[|\\]| )*1(\\+|\\-|\\(|\\)|\\[|\\]| )*
             2(\\+|\\-|\\(|\\)|\\[|\\]| )*9(\\+|\\-|\\(|\\)|\\[|\\]| )*
             8(\\+|\\-|\\(|\\)|\\[|\\]| )*0(\\+|\\-|\\(|\\)|\\[|\\]| )*
             7(\\+|\\-|\\(|\\)|\\[|\\]| )*4(\\+|\\-|\\(|\\)|\\[|\\]| )*
             0(\\+|\\-|\\(|\\)|\\[|\\]| )*';

问题是,当我得到像“11234567”这样的输入时,它就像“7311234567”,但没有“73”——当查询执行时——它也会找到带有“7311234567”的用户

问题:如何更好地包装我的regexp,使其只适合regexp的完整数字


共 (1) 个答案

  1. # 1 楼答案

    你可以使用这个MySQL package来让regexp_replace供你使用。 然后,您可以在搜索时替换所有非数字字符,从而避免对不同格式的测试

    String mobileInput = "(731) 123-4567";
    String mobile = mobileInput.replaceAll("[^0-9]", "");
    
    String sql = "select * from contact where regexp_replace(mobile, '[^0-9]', '') = ?";
    // run your sql query
    
    // or directly on database side without Java
    String sql = "select * from contact where regexp_replace(mobile, '[^0-9]', '') = regexp_replace(?, '[^0-9]', '')";
    

    通过删除非数字字符,(731) 123-4567731-123 45 67731-12-3-[4567]将为您提供7311234567

    使用Oracle进行测试,因为我没有安装MySQL:

    select regexp_replace('(731) 123-4567', '[^0-9]', '') as "first",
           regexp_replace('731-123 45 67', '[^0-9]', '') as "second",
           regexp_replace('731-12-3-[4567]', '[^0-9]', '') as "third"
      from dual
    

    ->

         first          second           third
    7311234567      7311234567      7311234567