如何在 MySQL 中的正则表达式替换

如何在 MySQL 中的正则表达式替换,第1张

mysql的正则匹配用regexp,而替换字符串用REPLACE(str,from_str,to_str)

举例如下:

UPDATE myTable SET HTML=REPLACE(HTML,'<br>','') WHERE HTML REGEXP '(<br */*>\s*){2,}'

达到的效果:会把所有<br>全部替换掉。

mysql中常用的替换函数

所用到的函数:

locate:

LOCATE(substr,str)

POSITION(substr IN str)

返回子串 substr 在字符串 str 中第一次出现的位置。如果子串 substr 在 str 中不存在,返回值为 0:

substring

SUBSTR(str,pos,len): 由<str>中的第<pos>位置开始,选出接下去的<len>个字元。

replace

replace(str1, str2, str3): 在字串 str1 中,当str2 出现时,将其以 str3 替代。

如果您觉得文本对您有帮助,请打赏,谢谢。

新建执行脚本:mysql_install.sh,并添加执行权限

#!/bin/bash

#zhouyihua V0.1 2021.07.08

#For centos 7.0 &8.0

#v 0.2

# add DNS

echo "----------  Add DNS  --------"

echo "nameserver 8.8.8.8" >>/etc/resolv.conf

#stop firewall

systemctl stop firewalld

if [ $? -ne 0 ]then

    echo "Firewall stop failed"

else

    echo "Firewall stop success"

fi

#download mysql yum source

wget https://dev.mysql.com/get/mysql80-community-release-el7-3.noarch.rpm

#install mysql yum source

rpm -ivh mysql80-community-release-el7-3.noarch.rpm

#enable 5.7

#sed -i '21s/enabled=0/enabled=1/g' /etc/yum.repos.d/mysql-community.repo

#sed -i '21s/enabled=0/enabled=1/g' /etc/yum.repos.d/mysql-community.repo

#disable 8.0

#sed -i '28s/enabled=1/enabled=0/g' /etc/yum.repos.d/mysql-community.repo

#install mysql

yum -y module disable mysql

yum -y remove mariadb-libs

yum install -y mysql-community-server

#config mysql

echo "-----------  Config my.cnf  ----------"

sed -i '/\[mysqld\]/a\lower_case_table_names=1' /etc/my.cnf

sed -i '/\[mysqld\]/a\skip-grant-tables' /etc/my.cnf

#start mysql

echo "----------  Starting mysql service  ----------"

systemctl start mysqld.service

mysql -uroot -p123456  <<EOF

    use mysql

    update user set authentication_string='' where user='root'

    flush privileges

    ALTER user 'root'@'localhost' IDENTIFIED BY '?CZJh8JWxvH';

EOF

echo "----------  Annotation skip grant tables in my.cnf    ----------"

sed -i 's/skip-grant-tables/\#skip-grant-tables/g' /etc/my.cnf

echo "----------  Restart mysql service  ----------"

systemctl restart mysqld.service

echo "----------  Grant all privileges  ----------"

mysql -uroot -p'Oracle1234!@#$'    --connect-expired-password -e "alter user 'root'@'localhost' identified by 'Oracle1234!@#$'"

mysql -u root -p'Oracle1234!@#$'  <<EOF

    use mysql

    CREATE USER 'maxkey'@'%' IDENTIFIED BY 'Oracle1234!@#$'

    GRANT ALL ON *.* TO 'maxkey'@'%'

EOF

参考:

先设置grant_skip_tables

  1.  use mysql

  2. update user set authentication_string='' where user='root'     如果这个字段有值,先置为空

  3. flush privileges    刷新权限表

  4.ALTER user 'root'@'localhost' IDENTIFIED BY 'Tianya1234'    修改root 密码

参考:https://blog.csdn.net/qq_27820551/article/details/101488430

MySQL 一直以来都支持正则匹配,不过对于正则替换则一直到MySQL 8.0 才支持。对于这类场景,以前要么在MySQL端处理,要么把数据拿出来在应用端处理。

比如我想把表y1的列str1的出现第3个action的子 串替换成dble,怎么实现?

1. 自己写SQL层的存储函数。代码如下写死了3个,没有优化,仅仅作为演示,MySQL 里非常不建议写这样的函数。

mysql

DELIMITER $$

USE `ytt`$$

DROP FUNCTION IF EXISTS `func_instr_simple_ytt`$$

CREATE DEFINER=`root`@`localhost` FUNCTION `func_instr_simple_ytt`(

f_str VARCHAR(1000), -- Parameter 1

f_substr VARCHAR(100),  -- Parameter 2

f_replace_str varchar(100),

f_times int -- times counter.only support  3.

) RETURNS varchar(1000)

BEGIN

declare v_result varchar(1000) default 'ytt'-- result.

declare v_substr_len int default 0-- search string length.

set f_times = 3-- only support  3.

set v_substr_len = length(f_substr)

select instr(f_str,f_substr) into @p1-- First real position .

select instr(substr(f_str,@p1+v_substr_len),f_substr) into @p2Secondary virtual position.

select instr(substr(f_str,@p2+ @p1 +2*v_substr_len - 1),f_substr) into @p3-- Third virtual position.

if @p1 >0  &&@p2 >0 &&@p3 >0 then -- Fine.

select

concat(substr(f_str,1,@p1 + @p2 + @p3 + (f_times - 1) * v_substr_len  - f_times)

,f_replace_str,

substr(f_str,@p1 + @p2 + @p3 + f_times * v_substr_len-2)) into v_result

else

set v_result = f_str-- Never changed.

end if

-- Purge all session variables.

set @p1 = null

set @p2 = null

set @p3 = null

return v_result

end

$$

DELIMITER

-- 调用函数来更新:

mysql>update y1 set str1 = func_instr_simple_ytt(str1,'action','dble',3)

Query OK, 20 rows affected (0.12 sec)

Rows matched: 20  Changed: 20  Warnings: 0

2. 导出来用sed之类的工具替换掉在导入,步骤如下:(推荐使用)

1)导出表y1的记录。

mysqlmysql>select * from y1 into outfile '/var/lib/mysql-files/y1.csv'Query OK, 20 rows affected (0.00 sec)

2)用sed替换导出来的数据。

shellroot@ytt-Aspire-V5-471G:/var/lib/mysql-files#  sed -i 's/action/dble/3' y1.csv

3)再次导入处理好的数据,完成。

mysql

mysql>truncate y1

Query OK, 0 rows affected (0.99 sec)

mysql>load data infile '/var/lib/mysql-files/y1.csv' into table y1

Query OK, 20 rows affected (0.14 sec)

Records: 20  Deleted: 0  Skipped: 0  Warnings: 0

以上两种还是推荐导出来处理好了再重新导入,性能来的高些,而且还不用自己费劲写函数代码。

那MySQL 8.0 对于以上的场景实现就非常简单了,一个函数就搞定了。

mysqlmysql>update y1 set str1 = regexp_replace(str1,'action','dble',1,3) Query OK, 20 rows affected (0.13 sec)Rows matched: 20  Changed: 20  Warnings: 0

还有一个regexp_instr 也非常有用,特别是这种特指出现第几次的场景。比如定义 SESSION 变量@a。

mysqlmysql>set @a = 'aa bb cc ee fi lucy  1 1 1 b s 2 3 4 5 2 3 5 561 19 10 10 20 30 10 40'Query OK, 0 rows affected (0.04 sec)

拿到至少两次的数字出现的第二次子串的位置。

mysqlmysql>select regexp_instr(@a,'[:digit:]{2,}',1,2)+--------------------------------------+| regexp_instr(@a,'[:digit:]{2,}',1,2) |+--------------------------------------+|                                   50 |+--------------------------------------+1 row in set (0.00 sec)

那我们在看看对多字节字符支持如何。

mysql

mysql>set @a = '中国 美国 俄罗斯 日本 中国 北京 上海 深圳 广州 北京 上海 武汉 东莞 北京 青岛 北京'

Query OK, 0 rows affected (0.00 sec)

mysql>select regexp_instr(@a,'北京',1,1)

+-------------------------------+

| regexp_instr(@a,'北京',1,1)   |

+-------------------------------+

|                            17 |

+-------------------------------+

1 row in set (0.00 sec)

mysql>select regexp_instr(@a,'北京',1,2)

+-------------------------------+

| regexp_instr(@a,'北京',1,2)   |

+-------------------------------+

|                            29 |

+-------------------------------+

1 row in set (0.00 sec)

mysql>select regexp_instr(@a,'北京',1,3)

+-------------------------------+

| regexp_instr(@a,'北京',1,3)   |

+-------------------------------+

|                            41 |

+-------------------------------+

1 row in set (0.00 sec)

那总结下,这里我提到了 MySQL 8.0 的两个最有用的正则匹配函数 regexp_replace 和 regexp_instr。针对以前类似的场景算是有一个完美的解决方案。


欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/7243869.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-04-03
下一篇 2023-04-03

发表评论

登录后才能评论

评论列表(0条)

保存