2013-05-15 46 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的子查詢展開爲電話號碼的最大長度。