0
votes

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.

1
Why not a normal String.replace('[', '{') (Even using String#replace(char, char) i.o. (String, String) or that regex replaceAll.Joop Eggen
I mean, not code level. This is an example format of input for array on competitive programming site. I'm using java(which uses {} for array initialization) I need to convert every time to paste that to my code.Heath Kim

1 Answers

2
votes

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