-1

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!

Xiahao Wang
  • 45
  • 1
  • 3
  • 10
  • 1
    Is it always one character per square brackets? – keyser May 25 '14 at 10:51
  • Apparently it isn't. Note that that's relevant information. A char is not the same as a string in java. And it matters for regex matching as well. – keyser May 25 '14 at 11:01

2 Answers2

1

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));

Pattern description

\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

Community
  • 1
  • 1
Braj
  • 46,415
  • 5
  • 60
  • 76
0

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));
Roman C
  • 49,761
  • 33
  • 66
  • 176