nus-cs2113-AY2122S2 / forum

3 stars 2 forks source link

how to replace "[" and "]" in a string #23

Closed Yzkkk closed 2 years ago

Yzkkk commented 2 years ago

Since [ and ] are special characters in a string, if i write something like String temp = a.replaceAll("[ ][hi]", "hey"); it is not going to work.

I remember we needed to use some '/' and '\' but couldn't remember exactly how :(

lithream commented 2 years ago

Use two backslashes before the [ brackets. Like so: String temp = a.replaceAll("\\[]\\[hi]", "hey");

I don't know why backslashes are not required for the ] brackets. I tried String temp = a.replaceAll("\\[\\]\\[hi\\]", "hey");

first and it gave me the same result, but IntelliJ recommended removing the apparently redundant escapes before the ] brackets so I did.

The string is treated as regex so it probably has something to do with that.

Yzkkk commented 2 years ago

thank you!