Search code examples
regexintellij-idea

How do I convert square brackets to curly bracket in text using by regular expression?


How do I convert square brackets to curly brackets in text using regular expression?

I'm trying to convert
[[0,0,0,0,0],[0,0,1,0,3],[0,2,5,0,1],[4,2,4,4,2],[3,5,1,3,1]]
this to
{{0,0,0,0,0},{0,0,1,0,3},{0,2,5,0,1},{4,2,4,4,2},{3,5,1,3,1}}

Can I do it in a simple way? I found this Link but it's PHP way.

I'm trying this on an IDE like IntelliJ or online regex tester like regex101.

Thanks.


Solution

  • In regex101 you can use the PCRE2 Replacement String Conditional trick.

    Pattern :

    (\[)|(\])
    

    Basically capture the brackets in seperate capture groups.

    Substitute :

    ${1:+\{:$1}${2:+\}:$2}
    

    Or the golfcoded version

    ${1:+\{:${2:+\}}}
    

    If group 1 not empty then replace with {.
    If group 2 not empty then replace with }.

    Test on regex101 here