如何在Java中提取包含多个括号的子字符串?

时间:2016-11-17 08:14:09

标签: java regex string

是否有正则表达式从包含多个parantheses的字符串中提取子字符串?

例如我的字符串是

String str = "(A(B(C(D(x)))))";

我想要打印任何一对parantheses中的所有子字符串:

  A(B(C(D(x))))
  B(C(D(x)))
  C(D(x))
  D(x)
  x

我尝试使用正则表达式:

        Matcher m = Pattern.compile("\\((.*?)\\)").matcher(str);
        while (m.find()) {
            System.out.println(m.group(1));
        }

但这只会提取它在第一对括号中找到的子字符串。

1 个答案:

答案 0 :(得分:1)

我已经开发了你所要求的但不仅仅是正则表达式,而是一个递归函数。请检查以下代码:

public static void main(String[] args)
{
    String str = "(A(B(C(D(x)))))";
    findStuff(str);

}

public static void findStuff(String str){
    String pattern = "\\((.+)\\)";

    Pattern p = Pattern.compile(pattern);
    Matcher m = p.matcher(str);
    while (m.find())
    {
        String sub = m.group(1);
        System.out.println(" Word: " + sub);

        findStuff(sub);
    }
}