Mitesh
Mitesh

Reputation: 165

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]

Upvotes: 1

Views: 1197

Answers (1)

rajuGT
rajuGT

Reputation: 6404

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.

Upvotes: 1

Related Questions