【问题标题】:How to replace non-numiric characters from a string MySQL如何从字符串 MySQL 中替换非数字字符
【发布时间】:2013-05-15 18:17:48
【问题描述】:

我需要一种更好的方法来替换字符串中的非数字字符。

我有这样的电话号码 (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

如何更改我的查询以使用 REGEX 替换非数字值。

谢谢

【问题讨论】:

  • 正如所有其他包含mysqlregex 的问题所表明的那样,这不是原生MySQL。你could use this.

标签: mysql regex replace


【解决方案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 的子查询扩展为电话号码的最大长度。

【讨论】:

    【解决方案2】:

    我不知道 mySql 正则表达式的风格,但我会试一试:

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

    [^\d]+ 表示:'匹配所有不是数字的东西,一次或多次'

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

    【讨论】:

    • 在 MySQL 中,无法使用正则表达式替换输出,而不是没有 3rd 方代码。但是您的正则表达式是正确的:)
    • 谢谢,这就是我要找的 :)
    • 我认为它有效,但它不起作用。它不会替换我的字符串中的所有字符
    猜你喜欢
    • 2012-09-04
    • 1970-01-01
    • 2013-07-18
    • 2017-07-09
    • 1970-01-01
    • 2012-10-10
    • 2010-09-20
    • 1970-01-01
    • 2011-08-22
    相关资源
    最近更新 更多