I want get the value inside []. For example, this string:
 String str ="[D][C][B][A]Hello world!";
and I want an array which contains item DCBA, how should I do this?
Thank you in advance!
I want get the value inside []. For example, this string:
 String str ="[D][C][B][A]Hello world!";
and I want an array which contains item DCBA, how should I do this?
Thank you in advance!
 
    
    Try with regex if there is only one character inside [].
Here Matcher#group() is used that groups any matches found inside parenthesis ().
Here escape character \ is used to escape the [ and ] that is already a part of regex pattern itself.
Sample code:
String str = "[D][C][B][A]Hello world!";
List<Character> list = new ArrayList<Character>();
Pattern p = Pattern.compile("\\[(.)\\]");
Matcher m = p.matcher(str);
while (m.find()) {
    list.add(m.group(1).charAt(0));
}
Character[] array = list.toArray(new Character[list.size()]);
System.out.println(Arrays.toString(array));
Try this one if there is more than one character inside []
String str = "[DD][C][B][A]Hello world!";
List<String> list = new ArrayList<String>();
Pattern p = Pattern.compile("\\[(\\w*)\\]");
Matcher m = p.matcher(str);
while (m.find()) {
    list.add(m.group(1));
}
String[] array = list.toArray(new String[list.size()]);
System.out.println(Arrays.toString(array));
\w      A word character: [a-zA-Z_0-9]
.       Any character (may or may not match line terminators)
X*      X, zero or more times
Read more about here JAVA Regex Pattern
This code is simple
  String str ="[D][C][B][A]Hello world!";
  String[] s =  str.split("\\[");
  StringBuilder b = new StringBuilder();
  for (String o: s) {
    if (o.length() > 0){
      String[] s2 =  o.split("\\]");
      b.append(s2[0]);
    }
  }
  char[] c = b.toString().toCharArray();
  System.out.println(new String(c));
