如何使用BNF词法分析器识别和提取简单的嵌套标记?

时间:2015-06-30 11:24:10

标签: lex bnf marpa

我不知道如何获得有关此内容的文档。我刚刚发现大多数编译器都使用Backus-Naur形式来描述一种语言。

Marpa::R2 perl包中,获取解析算术字符串的简单示例,例如42 * 1 + 7

:default ::= action => [name,values]
lexeme default = latm => 1

Calculator ::= Expression action => ::first

Factor ::= Number action => ::first
Term ::=
    Term '*' Factor action => do_multiply
    | Factor action => ::first
Expression ::=
    Expression '+' Term action => do_add
    | Term action => ::first
Number ~ digits
digits ~ [\d]+
:discard ~ whitespace
whitespace ~ [\s]+   

我想修改它以便递归地解析类似XML的示例,例如:

<foo>
    Some content here 
    <bar>
        I am nested into foo
    </bar>
    A nested block was before me.
</foo> 

并将其表达为:

>(Some content here)
>>(I am nested into foo)
>(A nested block was before me)

我可以使用此功能:

sub block($content, $level) {
    for each $content line
        $line = (">" x $level).$content
    return $content
}

对我来说是一个好的开始吗?

1 个答案:

答案 0 :(得分:3)

有一个开源Marpa-powered XML parser