Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do a regular expression replace in MySQL?

I have a table with ~500k rows; varchar(255) UTF8 column filename contains a file name;

I'm trying to strip out various strange characters out of the filename - thought I'd use a character class: [^a-zA-Z0-9()_ .\-]

Now, is there a function in MySQL that lets you replace through a regular expression? I'm looking for a similar functionality to REPLACE() function - simplified example follows:

SELECT REPLACE('stackowerflow', 'ower', 'over');  Output: "stackoverflow"  /* does something like this exist? */ SELECT X_REG_REPLACE('Stackoverflow','/[A-Zf]/','-');   Output: "-tackover-low" 

I know about REGEXP/RLIKE, but those only check if there is a match, not what the match is.

(I could do a "SELECT pkey_id,filename FROM foo WHERE filename RLIKE '[^a-zA-Z0-9()_ .\-]'" from a PHP script, do a preg_replace and then "UPDATE foo ... WHERE pkey_id=...", but that looks like a last-resort slow & ugly hack)

like image 836
Piskvor left the building Avatar asked Jun 12 '09 14:06

Piskvor left the building


People also ask

Can I use regex in replace?

How to use RegEx with . replace in JavaScript. To use RegEx, the first argument of replace will be replaced with regex syntax, for example /regex/ . This syntax serves as a pattern where any parts of the string that match it will be replaced with the new substring.

How do you replace something in MySQL?

MySQL REPLACE() FunctionThe REPLACE() function replaces all occurrences of a substring within a string, with a new substring. Note: This function performs a case-sensitive replacement.

What is regex replace in SQL?

REGEXP_REPLACE extends the functionality of the REPLACE function by letting you search a string for a regular expression pattern. By default, the function returns source_char with every occurrence of the regular expression pattern replaced with replace_string .


2 Answers

MySQL 8.0+:

You can use the native REGEXP_REPLACE function.

Older versions:

You can use a user-defined function (UDF) like mysql-udf-regexp.

like image 159
Jeremy Stein Avatar answered Oct 01 '22 00:10

Jeremy Stein


If you are using MariaDB or MySQL 8.0, they have a function

REGEXP_REPLACE(col, regexp, replace) 

See MariaDB docs and PCRE Regular expression enhancements

Note that you can use regexp grouping as well (I found that very useful):

SELECT REGEXP_REPLACE("stackoverflow", "(stack)(over)(flow)", '\\2 - \\1 - \\3') 

returns

over - stack - flow 
like image 25
Benvorth Avatar answered Sep 30 '22 23:09

Benvorth