Sai Sunder
Sai Sunder

Reputation: 1021

Replace everything between [ and ] in regex java

I need to remove everything between [ ].

Example:

My Input : ab[cd]e

Expected Output : abe.


I tried using \[ and \], but it is reported as an illegal escape sequence.

Can anyone please help me with this.

P.S.: I am using Java 1.7.

Upvotes: 14

Views: 23379

Answers (2)

Tadgh
Tadgh

Reputation: 2049

Try the replaceAll method

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

Upvotes: 7

João Silva
João Silva

Reputation: 91349

Use String#replaceAll:

String s = "ab[cd]e";
s = s.replaceAll("\\[.*?\\]", ""); // abe

This will replace [, ], and everything in between with an empty string.

Upvotes: 19

Related Questions