IAmYourFaja
IAmYourFaja

Reputation: 56912

How to strip braces out of Java string?

My Java app will be getting strings of the following form:

How now [[brown cow ]]. The arsonist [[ had oddly shaped ]] feet. The [[human torch was denied]] a bank loan.

And need a regex/method that would strip out every instance of [[ ]] (and all inclusive text), thus turning the above string into:

How now. The arsonist  feet. The  a bank loan.

Notice the preserved double-spaces (between arsonist and feet, and between The and a)? That's important too.

Not sure if a regex here is appropriate or if there is a more efficient way of culling out the unwanted [[ ]] instances.

Upvotes: 0

Views: 187

Answers (4)

MikeM
MikeM

Reputation: 13631

This is simple with replaceAll

str = str.replaceAll( "\\[\\[[^\\]]*\\]\\]", "" );

Assumes no ] between the brackets.

Upvotes: 2

Achintya Jha
Achintya Jha

Reputation: 12843

tring s = "How now [[brown cow ]]. The arsonist [[ had oddly shaped ]] feet. The [[human torch was denied]] a bank loan.";

s=s.replaceAll("\\[.*?\\]","").replace("]","");

Output:

How now . The arsonist  feet. The  a bank loan.

Upvotes: 2

Pankaj Phartiyal
Pankaj Phartiyal

Reputation: 1691

This is in javascript.

var text = "How now [[brown cow ]]. The arsonist [[ had oddly shaped ]] feet. The [[human torch was denied]] a bank loan."
text.replace(/\[\[[^\]]+\]\]/g, "")

The regex to match the braces will be

/\[\[[^\]]+\]\]/g

So Java equivalent will be

text.replaceAll("\[\[[^\]]+\]\]", "");

and replace it with an empty string

regex which can remove both double and triple braces

text.replaceAll("\[?\[\[[^\]]+\]\]\]?", "")

Upvotes: 3

Ankur Shanbhag
Ankur Shanbhag

Reputation: 7804

Try using this code :

public class Test{
public static void main(String[] args) {
    String input = "How now [[brown cow ]]. The arsonist [[ had oddly shaped ]] feet. The [[human torch was denied]] a bank loan.";
    // Will replace all data within braces []
    String replaceAll = input.replaceAll("(\\[.+?\\])|(\\])", "");
    System.out.println(replaceAll);
}

}

Hope this helps.

Upvotes: 2

Related Questions