简体   繁体   中英

MySQL Replace string from one character to another

I am dealing with string paths with have an array index in them, indicated by [#] where # is the index. This index can be anything. What I am trying to do is to in my path string, remove all the [#] occurrences. So brackets and anything within brackets to be removed. I see the replace function but I am not sure how to use an arbitrary “middle” between the brackets to replace.

I want to remove from '[' to ']' and replace this with '' .

Ex path: Number[2].padding[1] reduced to Number.padding .

Right now I have something like :

replace(path, '[%]', '') 

Where I'm trying to use % as a wildcard, but it is not functioning.

If you are using MySQL 8.0, you can use REGEXP_REPLACE to capture parts of string like [#] as follows

SELECT REGEXP_REPLACE(@txt, '\\[[^]]*\\]', '');

Regexp breakdown :

\\[      # opening square bracket
[^]]*    # 0 to N characters other than a closing square bracket 
\\]      # closing square bracket

Example with your test data :

SET @txt = 'Number[2].padding[1] reduced to Number.padding';
SELECT @txt input, REGEXP_REPLACE(@txt, '\\[[^]]*\\]', '') output

| input                                          | output                                   |
| ---------------------------------------------- | ---------------------------------------- |
| Number[2].padding[1] reduced to Number.padding | Number.padding reduced to Number.padding |

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