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.
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.
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.
\\s+ --> replaces 1 or more spaces. \\\\s+ --> replaces the literal \ followed by s one or more times.
$ means "Match the end of the string" (the position after the last character in the string).
Use String#replaceAll
:
String s = "ab[cd]e";
s = s.replaceAll("\\[.*?\\]", ""); // abe
This will replace [
, ]
, and everything in between with an empty string.
Try the replaceAll method
str = str.replaceAll("\\[.*?\\]","")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With