How to replace every other instance of a particular character in a MySQL string?

前端 未结 5 1200
梦毁少年i
梦毁少年i 2021-01-07 22:49

How to replace value in mysql column by query like, Column is options and its of type varchar(255)

From

id   options
1    A         


        
5条回答
  •  被撕碎了的回忆
    2021-01-07 23:16

    Demo

    Rextester demo

    Explanation

    This could be solved relatively easily if only MySQL had a regular expression replacement function but unfortunately it doesn't. So I wrote one - see this blog post. The "advanced version" is needed here to allows it to perform a recursive replace in the found match for the replacement. Then the following relatively simple SQL can be used:

    SQL (function code omitted for brevity)

    SELECT id,
           options AS `before`,
           reg_replace(options,
                       '\\|.*\\|', -- 2 pipe symbols with any text in between
                       '\\|$',     -- Replace the second pipe symbol
                       ',',        -- Replace with a comma
                       FALSE,      -- Non-greedy matching
                       2,          -- Min match length = 2 (2 pipe symbols)
                       0,          -- No max match length
                       0,          -- Min sub-match length = 1 (1 pipe symbol)
                       0           -- Max sub-match length = 1 (1 pipe symbol)
                       ) AS `after`
    FROM tbl;
    

提交回复
热议问题