在 MariaDB 中使用 REGEXP_REPLACE 进行正则表达式查找和替换的正确语法是什么?

2022-01-15 00:00:00 regex pcre mariadb mysql

我需要对名为 post 的 MySQL 表中名为 message 的列运行正则表达式查找和替换.

I need to run a regex find-and-replace against a column named message in a MySQL table named post.

我的数据库正在运行 MariaDB 10.

My database is running MariaDB 10.

根据 docs,MariaDB 10 有一个新的 REGEXP_REPLACE 函数,旨在完全做到这一点,但我似乎无法弄清楚实际的语法.

According to the docs, MariaDB 10 has a new REGEXP_REPLACE function designed to do exactly this, but I can't seem to figure out the actual syntax.

它将影响 280,000 行,因此理想情况下还有一种方法可以将其限制为在我测试时一次仅更改一个特定行,或者只是执行 SELECT 而不是 UPDATE 直到我确定它符合我的要求.

It will affect 280,000 rows, so ideally there's also a way to limit it to only changing one specific row at a time while I'm testing it, or simply doing a SELECT rather than an UPDATE until I'm sure it does what I want.

我要运行的正则表达式:[quotesauthor=(.+)slink=[^]]+]

The regex I want to run: [quotesauthor=(.+)slink=[^]]+]

替换字符串:[quote="$1"]

以下是我尝试过的,但它只是抛出了一个 SQL 错误:

The following was what I tried, but it just throws a SQL error:

UPDATE post SET message = REGEXP_REPLACE(message, '[quotesauthor=(.+)slink=[^]]+]', '[quote="$1"]') WHERE post_id= 12

在这种情况下,原始消息是:[quote author=Jon_doe link=board=2;threadid=125;start=40#msg1206 date=1065088] 最终结果应该是 [quote="Jon_doe"]

In this case, the original message was: [quote author=Jon_doe link=board=2;threadid=125;start=40#msg1206 date=1065088] and the end result should be [quote="Jon_doe"]

使这个 REGEXP_REPLACE 工作的正确语法是什么?

What is the proper syntax to make this REGEXP_REPLACE work?

推荐答案

这里要进行很多转义:

REGEXP_REPLACE(message, "\[quote\sauthor=(.+)\slink=[^\]]+]", "\[quote="\1"\]")

请注意,您必须通过 \1

相关文章