首页 > 解决方案 > 将字符串中的所有大括号导出到数组

问题描述

例子:

String = "(a(b[}7cv)))"

数组应如下所示:["(","(","[","}",")",")",")"]

我的尝试:

if(s.charAt(i) == "(" ){
    //add to array}

标签: javaarrayslistbraces

解决方案


您可以简单地使用正则表达式找到它们并将它们添加到列表中

  public static void main(String[] args) {
    String foo = "(a(b[}7cv)))";
    List<String> allMatches = new ArrayList<String>();
    Matcher m = Pattern.compile("\\W")
        .matcher(foo);
    while (m.find()) {
      allMatches.add(m.group());
    }
    System.out.println(allMatches); 
  }

如果它只是您所追求的括号,您可能希望将"[(){}\\]\\[]"其作为正则表达式Pattern.compile


推荐阅读