Parsing a string with nested brackets

别等时光非礼了梦想. 提交于 2019-12-12 04:49:21

问题


I'm writing a application to parse some commands. Commands are given in the form:

A { B }

I just want A and B. A is optional but that's easy enough to handle. The problem I'm having is that both A and B can contain almost any character including whitespace and '{' and '}'. The brackets need not be balanced, either. Is this possible to parse with a regex? If not, what is the simplest thing that you think could be done?

For example, given:

"parsme { foo { "hello" } { "goodbye" } {{{ } { bar { "up" } { "down" } }"

Then:

A = "parseme { foo { "hello" } { "goodbye" } {{{ }" and B = "bar { "up" } { "down" }"


回答1:


You can't use a regular expression to parse anything that requires arbitrary nesting like parenthesis (this is a well established limitation of regular expressions, a little googling here will help you).

You will need to use a context-free grammar for this using a tool like Antlr.



来源:https://stackoverflow.com/questions/10423970/parsing-a-string-with-nested-brackets

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!