是否可以使用正则表达式在完全括号表示中查找树的根?

时间:2015-05-28 12:14:39

标签: java regex

我希望找到树的根,当它以完整的括号形式表示时,如下所示:

(s (A (B b)(C c))(D (E e)))

我试过这个:

(\(\s*(\S+)\s+(\([.^\)]*\))*\))

但它与任何东西都不匹配。我想提取S及其叶子,在本例中它们是(A (B b)(C c))(D (E e))

我猜完全括号形式不是正则表达式。我对吗?

1 个答案:

答案 0 :(得分:2)

<强>问题

使用正则表达式无法解决此问题,因为要在其上使用的字符串集不构成常规语言。这种语言有点等同于平衡括号语言,它是一种无上下文语言。

<强>解决方案

解决此问题的一种方法是使用无上下文语法,但由于这不是标准的Java功能(据我所知),因此不建议在您的上下文中使用此策略。

更好的方法是使用堆栈(它为无上下文语言提供动力)。这个想法很简单:

parse the string from left to right
   create an empty stack
   if next char is '('
       throw it on the stack
   else if next char is ')'
       pop from stack
   if stack is empty
       current position is the root
       return substring from 0 to here as left leaves
       return substring from here to end as right leaves

这当然是伪代码。