Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace square brackets java

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?"

like image 702
Ema Avatar asked Nov 30 '22 23:11

Ema


2 Answers

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
like image 96
Sean Patrick Floyd Avatar answered Dec 12 '22 14:12

Sean Patrick Floyd


This should work:

.replaceAll("\\[.*?\\]", "").replaceAll(" +", " ");
like image 27
nhahtdh Avatar answered Dec 12 '22 13:12

nhahtdh