简体   繁体   English

如何使用 regexp_replace 将 mysql 中的多个字符替换为特定字符?

[英]How to replace multiple characters with a specific character in mysql with regexp_replace?

I am using regexp_replace to replace a field of type string having some special characters with '_' where ever those characters are present.我正在使用 regexp_replace 将具有某些特殊字符的字符串类型字段替换为存在这些字符的“_”。

I am using我在用

SELECT regexp_replace('name', ' |\-|\(|\)|\.', '_') from db.table;

Some values from the field 'name':

Pune Municipal Corp - Water
Kerala State Electricity Board Ltd. (KSEBL)
Paschim Gujarat Vij Company Limited (PGVCL)


What I want:

Pune_Municipal_Corp___Water
Kerala_State_Electricity_Board_Ltd___KSEBL_
Paschim_Gujarat_Vij_Company_Limited__PGVCL_

Try this尝试这个

SELECT  regexp_replace(name, '[^a-zA-Z0-9_]', '_') 

db<>fiddle db<>小提琴

I don't know what version of mysql you're using but, on mysql 8+ you can use the native REGEXP_REPLACE function.我不知道您使用的是什么版本的 mysql,但是在 mysql 8+ 上,您可以使用本机REGEXP_REPLACE function。

Otherwise if the version which you're using don't support regexp replace, you could just create a function to do that.否则,如果您使用的版本不支持正则表达式替换,您可以创建一个 function 来执行此操作。

Here is the function code:这是 function 代码:


DELIMITER $$

CREATE FUNCTION  `regex_replace`(pattern VARCHAR(1000),replacement VARCHAR(1000),original VARCHAR(1000))
RETURNS VARCHAR(1000)
DETERMINISTIC
BEGIN 
 DECLARE temp VARCHAR(1000); 
 DECLARE ch VARCHAR(1); 
 DECLARE i INT;
 SET i = 1;
 SET temp = '';
 IF original REGEXP pattern THEN 
  loop_label: LOOP 
   IF i>CHAR_LENGTH(original) THEN
    LEAVE loop_label;  
   END IF;
   SET ch = SUBSTRING(original,i,1);
   IF NOT ch REGEXP pattern THEN
    SET temp = CONCAT(temp,ch);
   ELSE
    SET temp = CONCAT(temp,replacement);
   END IF;
   SET i=i+1;
  END LOOP;
 ELSE
  SET temp = original;
 END IF;
 RETURN temp;
END$$

DELIMITER ;

Example using your regex and text:使用您的正则表达式和文本的示例:

mysql> select regex_replace('[ |\-|\(|\)|\.-]', '_', 'Pune Municipal Corp - Water Kerala State Electricity Board Ltd. (KSEBL) Paschim Gujarat Vij Company Limited (PGVCL)');

I got the code of the function here我在这里得到了 function 的代码

Hope this helps!希望这可以帮助!

You can simply use the translate to replace space and - with underscore( _ ) as follows:您可以简单地使用translate来替换space-下划线( _ ),如下所示:

Select translate(your_column, ' -', '__') from your_table

Db<>fiddle demo Db<>小提琴演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM