Mitesh Mitesh - 1 year ago 64
Java Question

Need to remove extra square brackets in the string

static ArrayList<String> coordinates = new ArrayList<String>();
static String str = "";
static ArrayList scribbles = new ArrayList();

coordinates.add("String to be placed, String not to be placed");
String codChange = coordinates.toString().replaceAll(", ", "");
StringBuffer sb = new StringBuffer(codChange);
sb.insert(1,"m ");
ArrayList aListNumbers = new ArrayList(Arrays.asList(sb.toString()));
System.out.println("Coordinates: " + aListNumbers.toString().replaceAll("\\[|\\]", ""));
str = scribbles.toString();
System.out.println("String: " + str);


Coordinates: m String to be placedString not to be placed
String: [[m String to be placedString not to be placed]]

I want the String: to appear with single square brackets like:

String: [m String to be placedString not to be placed]

Answer Source

Since there are two different replacement required.

Use below code

String s = "[[m String to be placedString not to be placed]]";

If you are sure about always the exact position of [[ is at the beginning and ]] is at end, just use substring as suggested in the other answer in the same SO answer thread.