-3

I have a string arraylist that it prints this: [[aaa,bbb,..,fff]] I havent made it to figure out why the double brackets are happening, as if i have 2 arrays inside each other. So I decided to use regex. What should I use to remove the inside brackets?

user2598911
  • 379
  • 2
  • 6
  • 22

4 Answers4

1

This will fix the problem:

String str = "[[aaa,bbb,..,fff]]";
str = str.replaceAll("\\[\\[", "[");
str = str.replaceAll("\\]\\]", "]");

However,

I havent made it to figure out why the double brackets are happening

That is something you should really investigate, rather than just fixing the symptom, find and fix the cause.

StormeHawke
  • 5,987
  • 5
  • 45
  • 73
  • `String.replaceAll()` expects a regex as its first argument. I don't think this will work since `[` has a special meaning in regex. Try instead `str.replace("[[", "[")` since `replace()` expects a literal string for its first argument and not a regex. – dcsohl Oct 04 '13 at 16:06
  • http://stackoverflow.com/questions/19158655/converting-string-array-to-list-double-brackets – user2598911 Oct 04 '13 at 16:15
  • @dcsohl edited my answer. Just forgot to escape the `[` and `]` characters – StormeHawke Oct 04 '13 at 16:23
  • 1
    @Cruncher, I was referring to this method: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html#replace%28java.lang.CharSequence,%20java.lang.CharSequence%29 - `String` is a subclass of `CharSequence`, so it works. Did you try it? – dcsohl Oct 04 '13 at 16:28
0
str.replaceAll("\\[(.*)\\]", "$1")
Rafi Kamal
  • 4,522
  • 8
  • 36
  • 50
0

If the brackets are always on the end then

str = str.substring(1, str.length()-2);

would be the easiest. However, if this is part of a larger string, then regex like the other answers is best.

And, like others have told you, find the problem, don't just band-aid it.

Cruncher
  • 7,641
  • 1
  • 31
  • 65
0

I would not rely on the toString() method concatenating a String list... I'd much rather advise an utility method - if you don't want to use any external libraries.

public static String getFormattedString(Collection<String> input, String separator)
   StringBuilder sb = new StringBuilder();
   boolean first = true;
   for(String s: input) {
     if(!first) {
       sb.append(separator);
     } else {
       first = false;
     }
     sb.append(s);
   }
   return sb.toString();
}

And in your code:

String result = getFormattedString(myStringList, ", ");

By doing this, it will be sure that you get the output you want, no matter what implementation you use...

If external libraries are OK, then you should not reinvent the wheel...

Apache Commons: StringUtil

String result = org.apache.commons.lang.StringUtils.join(myStringList, ", ");

Guava: Joiner

String result = com.google.common.base.Joiner.on(", ").join(myStringList);

(used info from this question, and its answers)

Community
  • 1
  • 1
ppeterka
  • 20,583
  • 6
  • 63
  • 78