清理具有特殊字符和字母的电话号码

时间:2016-06-22 22:06:45

标签: sql postgresql

我在电话号码字段中有垃圾,我想清理它们。我想知道如何查询以检查电话号码字段中是否有任何特殊字符,字母。有人可以帮忙吗? 我尝试了这个查询并且没有工作。我需要PostgreSQL中的代码

select phone from table where phone like '[^[:alpha:]]' and phone <>''
-- and phone not like '[^0-9]'
order by phone

表中的输入值如下所示:

Phone
-----
(443)-554-6677
111-111-1111
345-rty-34fr
4345434444 ext

输出(应该看起来像这个有效的电话号码)

(443)-554-6677
111-111-1111

感谢您的帮助。

谢谢你, Swathi。

1 个答案:

答案 0 :(得分:1)

我们可以使用POSIX regular expressions来获取所需的输出:

select phone from t1 where phone<>'' and phone!~'[[:alpha:]]';

output

您似乎尝试使用like运算符使用正则表达式语法,但这不正确。 like operator非常有限;它基本上只提供%前缀/后缀通配符和_单字符通配符。

如果你想更加严格,我们可以这样做:

select phone from t1 where phone~'^(\([0-9]{3}\)|[0-9]{3})-[0-9]{3}-[0-9]{4}$';

output

测试夹具

drop table if exists t1;
create table t1 (phone text);
insert into t1 (phone) values ('(443)-554-6677'), ('111-111-1111'), ('345-rty-34fr'), ('4345434444 ext');