Mitesh Mitesh - 2 months ago 8
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("\\[|\\]", ""));
scribbles.add(aListNumbers);
str = scribbles.toString();
System.out.println("String: " + str);


OUTPUT:

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

Since there are two different replacement required.

Use below code

String s = "[[m String to be placedString not to be placed]]";
System.out.println(s.replaceAll("[[","[").replaceAll("]]","]");

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.

Comments