获取出现多次的子串?

Obtain a substring that occurs multiple times?

String str="The colors are [blue], [yellow], and [green]";

我看过很多关于如何使用正则表达式实现这一点的帖子。

Here is my for loop that keeps giving me a string out of range error:
   for (int i=0;i<str.length();i++){
      String result = str.substring(str.indexOf("[") + 1, str.indexOf("]"));
      System.out.println(result);

我会说,如果您出于任何原因绝对不想使用正则表达式,那么您想要类似的东西。 Regex 几乎肯定会同样快并且代码看起来更漂亮。但无论如何,这里有一个示例代码:

String str="The colors are [blue], [yellow], and [green]";

ArrayList<String> arr = new ArrayList<String>();

for(int i = str.indexOf('[', 0); i != -1; i = str.indexOf('[', i + 1)) {
    arr.add(str.substring(i + 1, str.indexOf(']', i)));
}

for(String s : arr) {
    System.out.println(s);
}