2013-05-15 45 views
0

我需要一个更好的方法来替换字符串中的非数字字符。如何从字符串中替换非numiric字符MySQL

我的电话号码,像这样 (888)488-6655 888-555-8888 等等等等

所以我可以用一个简单的替换函数返回一个字符串,干净,但我期待更好的方法可能是使用表达式函数来替换任何非数字值。像空间斜杠,反斜杠,报价.....任何没有数值

这是我当前的查询

SELECT 
a.account_id, 
REPLACE(REPLACE(REPLACE(REPLACE(t.phone_number, '-', ''), ' ', ''), ')', ''),'(','') AS contact_number, 
IFNULL(t.ext, '') AS extention, 
CASE WHEN EXISTS (SELECT number_id FROM contact_numbers WHERE main_number = 1 AND account_id = a.account_id) THEN 0 ELSE 1 END AS main_number, 
'2' AS created_by 
FROM cvsnumbers t 
INNER JOIN accounts a ON a.company_code = t.company_code 
WHERE REPLACE(REPLACE(REPLACE(REPLACE(t.phone_number, '-', ''), ' ', ''), ')', ''),'(','') NOT IN(SELECT contact_number FROM contact_numbers WHERE account_id = a.account_id) 
AND LENGTH(REPLACE(REPLACE(REPLACE(REPLACE(t.phone_number, '-', ''), ' ', ''), ')', ''),'(','')) = 10 

我怎样才能改变我的查询使用一个正则表达式来代替非数字值。

感谢

+0

由于所有其他包含'mysql'&'regex'的问题都表明,这不是本机'MySQL'。你[可以使用这个](https://launchpad.net/mysql-udf-regexp)。 – Wrikken

回答

0

我不知道MySQL的正则表达式的味道,但我想给这个一展身手:

REPLACE(t.phone_number, '[^\d]+', '') 

[^\d]+表示:“比赛的一切,是不是一个数字,一次或多次”

您可能需要转义反斜杠([^\\d]+)。

+0

在MySQL中,不能使用正则表达式替换输出,而不是没有第三方代码。 但你的正则表达式是正确的:) – B8vrede

+0

感谢这就是我正在寻找:) – Mike

+0

我认为它的工作,但它不工作。它不会替换我的字符串中的所有字符 – Mike

1

这是一个蛮力的方法。

这个想法是创建一个数字表,它将索引电话号码中的每个数字。保留数字,如果它是数字,然后将它们组合在一起。这是它将如何工作:

select t.phone_number, 
     group_concat(SUBSTRING(t.phone_number, n.n, 1) separator '' order by n 
        ) as NumbersOnly 
from cvsnumbers t cross join 
    (select 1 as n union all select 2 union all select 3 
    ) n 
where SUBSTRING(t.phone_number, n.n, 1) between '0' and '9' 
group by t.phone_number; 

这个例子只看数字中的前3位数字。您可以将n的子查询展开为电话号码的最大长度。