replace square brackets java
10,689
Solution 1
String newStr = str.replaceAll("\\[\\d+\\] ", "");
What this does is to replace all occurrences of a regular expression with the empty String.
The regular expression is this:
\\[ // an open square bracket
\\d+ // one or more digits
\\] // a closing square bracket
// + a space character
Here's a second version (not what the OP asked for, but a better handling of whitespace):
String newStr = str.replaceAll(" *\\[\\d+\\] *", " ");
What this does is to replace all occurrences of a regular expression with a single space character.
The regular expression is this:
* // zero or more spaces
\\[ // an open square bracket
\\d+ // one or more digits
\\] // a closing square bracket
* // zero or more spaces
Solution 2
This should work:
.replaceAll("\\[.*?\\]", "").replaceAll(" +", " ");
Solution 3
Please use this,
String str = "[How are you]";
str = str.replaceAll("\\[", "").replaceAll("\\]","");
Author by
Ema
Updated on June 09, 2022Comments
-
Ema almost 2 years
I want to replace text in square brackets with "" in java:
for example I have the sentence
"Hello, [1] this is an example [2], can you help [3] me?"
it should become:
"Hello, this is an example, can you help me?"
-
beerbajay almost 12 yearsWhy would you assume that multiple spaces should be replaced?
-
Edwin almost 12 yearsGood, but you should add an extra space to the front of the expression to get rid of extra spacing.
-
Petr Janeček almost 12 years@beerbajay From the example, where "Hello, [1] this" became "Hello, this"
-
nhahtdh almost 12 years@beerbajay: From the sample output.
-
Sean Patrick Floyd almost 12 years@Edwin I added that to the back, but you are right, the front is better
-
Benjamin Gruenbaum almost 12 yearsGood solution, I'd just like to note the usage of reluctant quantifiers here is why this works meaning it catches [1] instead of [1] this is an example [2] .
-
Sean Patrick Floyd almost 12 yearsAdded a second version that addresses space
-
nhahtdh almost 12 yearsI'm not sure about all the inputs available, but I prefer not to process the space along with the tag. Inputs such as
[1] A B [4], C D [5] E F [8].
may not be processed correctly.