使用Regex拆分复杂的字符串

时间:2012-05-12 10:33:44

标签: regex string split

我正试图以一种特定的方式分割字符串。我一直在使用.split().replaceall()方法,但我无法正确使用它。

以下是我需要分割的字符串的几个示例,然后是分割后它们必须如何分割。 ,表示数组中的新字符串。

示例1:"(and (or (can-hit-robot) (wall) ) (can-hit-robot) (wall) ) )"

"(and", "(or", "(can-hit-robot)", "(wall)", ")", "(can-hit-robot)", "(wall)", ")"

示例2:"(seq (shoot) (if (can-hit-robot) (shoot) (move) ) )"

"(seq", "(shoot)", "(if", "(can-hit-robot)", "(shoot)", "(move)", ")", ")"

示例3:"(while(wall)(if (can-hit-robot)(shoot)(move)))"

"(while", "(wall)", "(if", "(can-hit-robot)", "(shoot)", "(move)", ")", ")"

非常感谢任何帮助!

4 个答案:

答案 0 :(得分:1)

这是怎么回事?

(?:\s*(?=\())|(?:(?<=\))\s*)

它依赖于lookbehind,所以没有lookbehind的引擎可能无法处理这个表达式。 :(

表达的规则是,在左括号之前和右括号之后分割,也切除括号外侧的任何空格。交替的左侧部分因此匹配通向开口的空间;正确的部分将匹配关闭后的空格。

答案 1 :(得分:1)

没有后悔断言:你可以拆分

\s*(?=\(|\B\))

这在开括号或右括号(包括空格)之前分割,但前提是我们在右括号之前不在单词边界。

输入:(and (or (can-hit-robot) (wall) ) (can-hit-robot) (wall) ) )

输出:

(and 
(or 
(can-hit-robot) 
(wall) 
) 
(can-hit-robot) 
(wall) 
) 
)

输入:(while(wall)(if (can-hit-robot)(shoot)(move)))

输出:

(while
(wall)
(if 
(can-hit-robot)
(shoot)
(move)
)
)

答案 2 :(得分:0)

你显然有语法。不要用正则表达式解析它,使用真正的解析器。

建议:

或许您应该首先阅读有关Parsing的内容。

否则,Cthulhu is calling

答案 3 :(得分:0)

不是你要求的,但我认为你最好还是写一个合适的解析器。我想你想以某种方式评估这个表达式?然后,您可以将输入解析为树,这将使您的评估更容易。

以第一个例子(and (or (can-hit-robot) (wall) ) (can-hit-robot) (wall) ) )为例,递归下降解析器将读取and,然后找到一个新的子表达式((or (can-hit-robot) (wall) ) (can-hit-robot) (wall) )),开始and的新子项((or (can-hit-robot) (wall) )),等等。

相关问题