Amine Hatim
Amine Hatim

Reputation: 247

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

Upvotes: 0

Views: 2644

Answers (4)

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

^, [ and ] are special characters that you need to escape first that is why it doesn't work which can be done by prefixing each special character with \\.

If you want to remove everything between [^ and ] you can use \\[\\^[^]]*\\] as regular expression defining a character sequence:

  1. Starting with [^,
  2. Containing a sequence of 0 or more of any characters except ],
  3. Then ]:

The corresponding code:

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

Upvotes: 1

Brij
Brij

Reputation: 269

just add \\ and string will look like

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

Upvotes: 1

you regex is not correct

use something like

String str = "test this a [^architecture.jpg]" + "lorem epsum" + "lorem epsum" + "[^rct.png]" + "lorem epsum";
String foo = "(?s)\\[\\^.+?\\]";
System.out.println(str.replaceAll(foo, ""));

the output is:

test this a lorem epsumlorem epsumlorem epsum

Upvotes: 2

resueman
resueman

Reputation: 10613

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("\\[\\^.*?\\]", "");

Upvotes: 3

Related Questions