Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace everything between [ and ] in regex java

Tags:

java

regex

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.

like image 668
Sai Sunder Avatar asked Sep 30 '12 19:09

Sai Sunder


People also ask

Can we use regex in replace Java?

regex package for searching and replacing matching characters or substring. Since String is immutable in Java it cannot be changed, hence this method returns a new modified String. If you want to use that String you must store it back on the relevant variable.

How do you find and replace in a regular expression in Java?

They can be used to search, edit, or manipulate text and data. The replaceFirst() and replaceAll() methods replace the text that matches a given regular expression. As their names indicate, replaceFirst replaces the first occurrence, and replaceAll replaces all occurrences.

What does replaceAll \\ s+ do?

\\s+ --> replaces 1 or more spaces. \\\\s+ --> replaces the literal \ followed by s one or more times.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).


2 Answers

Use String#replaceAll:

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

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

like image 123
João Silva Avatar answered Sep 20 '22 14:09

João Silva


Try the replaceAll method

str = str.replaceAll("\\[.*?\\]","")
like image 31
Tadgh Avatar answered Sep 20 '22 14:09

Tadgh