1

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.

5
  • dev.mysql.com/doc/refman/5.7/en/string-functions.html Commented Feb 13, 2019 at 22:18
  • I’m not sure which one you are pointing to. I know about replace and I’ve thought along the lines of a substring, but I can’t seem to find one that can specify from one character to another character Commented Feb 13, 2019 at 22:21
  • 2
    You could always try REGEX Commented Feb 13, 2019 at 22:23
  • How deep can the paths be? Commented Feb 14, 2019 at 0:56
  • they can be "infinitely" deep Commented Feb 14, 2019 at 14:04

1 Answer 1

2

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 |
Sign up to request clarification or add additional context in comments.

8 Comments

Great answer. Similar to what I figured out but a much better detailed answer with output. Also I didn't know about the carrot so that could've had consequences. Thank you!
it seems that I am not using MySQL 8.0 afterall. Is there a way to do this without REGEXP_REPLACE?
I am trying get the array brackets and text out of a path so I can compare to my parameter variable path.
@C.Programming ... without REGEXP_REPLACE, this will probably be painful... Question : is this always a one-digit number that is within the brackets, or it may be more than one digit ?
there may be more than one digit
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.