Can MySQL replace multiple characters?

前端 未结 6 2084
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-11-27 05:42

I\'m trying to replace a bunch of characters in a MySQL field. I know the REPLACE function but that only replaces one string at a time. I can\'t see any appropriate function

6条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-27 06:15

    REPLACE does a good simple job of replacing characters or phrases everywhere they appear in a string. But when cleansing punctuation you may need to look for patterns - e.g. a sequence of whitespace or characters at particular parts of the text, e.g. in the middle of a word or after a full stop. If that's the case, a regular expression replace function would be much more powerful.


    UPDATE: If using MySQL version 8+, a REGEXP_REPLACE function is provided and can be invoked as follows:

    SELECT txt,
           REGEXP_REPLACE(REPLACE(txt, ' ', '-'),
                          '[^a-zA-Z0-9-]+',
                          '') AS `reg_replaced`
    FROM test;
    

    See this DB Fiddle online demo.


    PREVIOUS ANSWER - only read on if using a version of MySQL before version 8: .

    The bad news is MySQL doesn't provide such a thing but the good news is it's possible to provide a workaround - see this blog post.

    Can I replace or delete multiple strings at once? For example I need to replace spaces with dashes and remove other punctuation.

    The above can be achieved with a combination of the regular expression replacer and the standard REPLACE function. It can be seen in action in this online Rextester demo.

    SQL (excluding the function code for brevity):

    SELECT txt,
           reg_replace(REPLACE(txt, ' ', '-'),
                       '[^a-zA-Z0-9-]+',
                       '',
                       TRUE,
                       0,
                       0
                       ) AS `reg_replaced`
    FROM test;
    

提交回复
热议问题