3

I just upgraded MySQL to 8.0.11 to be able to use the regexp_replace. It works fine in a select statement, but when I use the same in an update, I get strange results. Here is a simplified example: if I have a field with "567890", and I updated it with this:

update test set field = regexp_replace(field, '[7]', 'z')

instead of "56z890", the field value is set to "56".

This must be a bug, but in the meantime, are there any workarounds to get it to work as expected? Thanks.

2

2 Answers 2

4

It looks like a bug of the REGEXP_REPLACE function. In MariaDB it works as expected, see dbfiddle.

I'll try to report the bug in bugs.mysql.com. Bug was already reported, Bug #90803 regexp_replace accumulating result and Bug #90870 REGEXP_REPLACE truncate UPDATE.

A workaround is:

UPDATE `test`
SET `field` = CAST(REGEXP_REPLACE(`field`, '[7]', 'z') AS CHAR);

See dbfiddle.

3
  • Yes, that workaround did fix it for a replace of one record. Then I tested a SELECT over a set of records, and the output is somehow adding the results of one record to the results of the next record. So by the end it is one concatenation of all the previous records. Doing it with an actual update could be disastrous, so I think I'll wait until the next revision comes out. Thanks again. May 13, 2018 at 1:45
  • Bug #90803 describes the second issue I found, in my previous comment. But this seems separate from my original issue, where a replace on a single row is truncating the result. May 14, 2018 at 13:50
  • @RayGurganus: New bug reported, Bug #90870. See updated answer.
    – wchiquito
    May 15, 2018 at 13:00
1

I'm using Apache Version(PHP) 5.6 and MySQL version 10.1.25-Maria DB Localhost Server.

I've tried with the following query,

UPDATE `table_name` 
SET         
    column_name = REGEXP_REPLACE(column_name,regex_pattern_to_find,replaceable_text)
WHERE
    column_name RLIKE 'regex_pattern_to_find'

It was working fine for me. Hope this helps.

2
  • Why filter using where condition when regexp_replace already replace the targeted pattern ? Some kind of security ?
    – Heraknos
    Apr 15, 2021 at 15:12
  • @Heraknos If you don't add the where condition, the query will check all the rows and update if the regex condition is matched. It'll consume more time when you've more rows, so we just have to filter the rows first and then replace the column further. Hope it helps ;) Apr 16, 2021 at 10:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.