Amine Hatim Amine Hatim - 10 days ago 7
Java Question

Remove string between two chars

I have this String


test this a [^architecture.jpg]
lorem epsum
lorem epsum
[^rct.png]
lorem epsum



I need to remove string between [^ and ]

to get something like

test this a
lorem epsum
lorem epsum
lorem epsum


I tried this regex in JAVA

str = str.replaceAll("[^.*?]", "");


But it doesn't worked

Would you have any ideas please ?

Best regards

Answer

It's happening because you're not escaping these characters: []^, so they're being treated as special characters in the regex. Basically, right now it's replacing any character which is not ., *, or ?, which just leaves you with the two periods. Just add \\ before each of them to escape them, and it will work like you want.

str = str.replaceAll("\\[\\^.*?\\]", "");