replace square brackets java
brackets, java, replace
Solution
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
Problem
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?"