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("\\]","");
Share:
10,689
Ema
Author by

Ema

Updated on June 09, 2022

Comments

  • Ema
    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
    beerbajay almost 12 years
    Why would you assume that multiple spaces should be replaced?
  • Edwin
    Edwin almost 12 years
    Good, but you should add an extra space to the front of the expression to get rid of extra spacing.
  • Petr Janeček
    Petr Janeček almost 12 years
    @beerbajay From the example, where "Hello, [1] this" became "Hello, this"
  • nhahtdh
    nhahtdh almost 12 years
    @beerbajay: From the sample output.
  • Sean Patrick Floyd
    Sean Patrick Floyd almost 12 years
    @Edwin I added that to the back, but you are right, the front is better
  • Benjamin Gruenbaum
    Benjamin Gruenbaum almost 12 years
    Good 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
    Sean Patrick Floyd almost 12 years
    Added a second version that addresses space
  • nhahtdh
    nhahtdh almost 12 years
    I'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.