Ema
Ema

Reputation: 241

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

Upvotes: 4

Views: 11636

Answers (3)

Mohammed Shaheen MK
Mohammed Shaheen MK

Reputation: 1219

Please use this,

String str = "[How are you]";
str = str.replaceAll("\\[", "").replaceAll("\\]","");

Upvotes: 2

Sean Patrick Floyd
Sean Patrick Floyd

Reputation: 298838

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

Upvotes: 14

nhahtdh
nhahtdh

Reputation: 56809

This should work:

.replaceAll("\\[.*?\\]", "").replaceAll(" +", " ");

Upvotes: 4

Related Questions