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 楼答案
你可以使用这个MySQL package来让
regexp_replace
供你使用。 然后,您可以在搜索时替换所有非数字字符,从而避免对不同格式的测试通过删除非数字字符,
(731) 123-4567
、731-123 45 67
和731-12-3-[4567]
将为您提供7311234567
使用Oracle进行测试,因为我没有安装MySQL:
->