Reputation: 247
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
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:
[^
, 0
or more of any characters except ]
, ]
:The corresponding code:
str = str.replaceAll("\\[\\^[^]]*\\]", "");
Upvotes: 1
Reputation: 269
just add \\ and string will look like
str = str.replaceAll("\\[\\^.*?\\]", "");
Upvotes: 1
Reputation: 48258
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
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