解析带有嵌套括号的字符串 [英] Parsing a string with nested brackets

查看:375
本文介绍了解析带有嵌套括号的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个应用程序来解析一些命令.命令以以下形式给出:

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

A {B}

我只想要A和B.A是可选的,但操作起来很容易.我遇到的问题是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?

例如,给定:

"parsme {foo {" hello} {"再见} {{{}} bar {向上"} {向下"}}"

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

然后:

A ="parseme {foo {" hello} {"再见} {{{}"和B ="bar {"上} {"下}"

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

推荐答案

您不能使用正则表达式来解析任何需要任意嵌套的内容,例如括号(这是对正则表达式的明确限制,在此处进行一些谷歌搜索帮你).

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).

您将需要使用类似Antlr的工具来使用上下文无关的语法.

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

这篇关于解析带有嵌套括号的字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆