MySQL : how to remove double or more spaces from a string?

前端 未结 11 1306
南方客
南方客 2020-12-03 08:12

I couldn\'t find this question for MySQL so here it is:

I need to trim all double or more spaces in a string to 1 single space.

For example: \"The  

11条回答
  •  爱一瞬间的悲伤
    2020-12-03 08:14

    Follow my generic function made for MySQL 5.6. My intention was to use regular expression to identify the spaces, CR and LF, however, it is not supported by this version of mysql. So, I had to loop through the string looking for the characters.

    CREATE DEFINER=`db_xpto`@`%` FUNCTION `trim_spaces_and_crlf_entire_string`(`StringSuja` text) RETURNS text CHARSET utf8     COLLATE utf8_unicode_ci
    DETERMINISTIC
    BEGIN
    DECLARE StringLimpa TEXT;
    DECLARE CaracterAtual, CaracterAnterior TEXT;
    DECLARE Contador, TamanhoStringSuja INT;
    
    SET StringLimpa = '';
    SET CaracterAtual = '';
    SET CaracterAnterior = '';
    SET TamanhoStringSuja = LENGTH(StringSuja);
    SET Contador = 1;
    
    WHILE Contador <= TamanhoStringSuja DO
        SET CaracterAtual = SUBSTRING(StringSuja, Contador, 1);
    
        IF ( CaracterAtual = ' ' AND CaracterAnterior = ' ' ) OR CaracterAtual = '\n' OR CaracterAtual = '\r' THEN
            /* DO NOTHING */
            SET Contador = Contador;
            /* TORNA OS ESPAÇOS DUPLICADOS, CR, LF VISUALIZÁVEIS NO RESULTADO (DEBUG)
            IF ( CaracterAtual = ' ' ) THEN SET StringLimpa = CONCAT(StringLimpa, '*');END IF;
            IF ( CaracterAtual = '\n' ) THEN SET StringLimpa = CONCAT(StringLimpa, '\\N');END IF;
            IF ( CaracterAtual = '\r' ) THEN SET StringLimpa = CONCAT(StringLimpa, '\\R');END IF;
            */
        ELSE
            /* COPIA CARACTER ATUAL PARA A STRING A FIM DE RECONSTRUÍ-LA SEM OS ESPAÇOS DUPLICADOS */
            SET StringLimpa = CONCAT(StringLimpa, CaracterAtual);
            /*SET StringLimpa = CONCAT(StringLimpa, Contador, CaracterAtual);*/
            SET CaracterAnterior = CaracterAtual;
        END IF;
    
        SET Contador = Contador + 1;
    END WHILE;
    
    RETURN StringLimpa;
    END
    

提交回复
热议问题