简体   繁体   中英

How to trim all leading and trailing whitespace from all values of a MariaDB column

I want to trim all leading and trailing whitespace (spaces, linebreaks, tabs, etc) from all values of a MariaDB column. The values may contain new-lines, and the trimming is supposed to treat the whole multi-line value as one String (basically like String.trim() works in Java).

I am aware of the TRIM() function that only trims off one character type at a time. It seems too tedious for this purpose.

I was hoping to use REGEXP_REPLACE (available since MariaDB 10.0.5) for something like

UPDATE my_table SET my_column = REGEXP_REPLACE(my_column, '^[^\\s]*(?s)(.*)[^\\s]*$', '\\1');

but that didn't work.

Your regex pattern is off, and you should just be using \\s to capture whitespace:

UPDATE my_table
SET my_column = REGEXP_REPLACE(my_column, '^\\s*(.*?)\\s*$', '\\1');

Demo

(demo shown in MySQL 8.0, as the MariaDB demo was having issues, though the only difference is that MySQL uses $1 as the capture group instead of \\\\1 )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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