使用MARPA :: R2 perl解析双引号字符串

时间:2018-03-20 23:58:20

标签: regex perl marpa

我正在使用MARPA :: R2实现解析器。

我有G1 rule喜欢:

PARAM ::= STRING | REGEX_STRING

L0 rule喜欢:

STRING                     ~ [^ \/\(\),&:\"~]+   -----> works fine
REGEX_STRING               ~ [\"([^:]*?)\"] -----> doesn't work

使用REGEX_STRING,我正在尝试解析用双引号括起来的字符串,但正则表达式出了问题。此外,我想删除双引号,只保留引号之间的内容。

所以,如果我使用下面的代码给出输入:

my $recce = Marpa::R2::Scanless::R->new({grammar => $grammar});
my $input = "\"foo\"";  --> here, it should parse "foo" and give me foo.
print "Trying to parse:\n$input\n\n";
$recce->read(\$input);
my $value_ref = ${$recce->value};
print "Output:\n".Dumper($value_ref);

其他例子:“bar123”,“foo(123)”等。

2 个答案:

答案 0 :(得分:3)

use 5.026;
use strictures;
use Data::Dumper qw(Dumper);
use Marpa::R2 qw();

my $grammar = Marpa::R2::Scanless::G->new({
    bless_package => 'parsetree',
    source        => \<<'',
:default ::= action => [values] bless => ::lhs
lexeme default = action => [ start, length, value ] bless => ::name latm => 1
:start ::= expression
expression ::= funcname params
params ::= epsilon | lparen param rparen
epsilon ::=
funcname ~ [a-z0-9]+
lparen ~ '('
param ::= unquotedparam | quotedparam
unquotedparam ::= [a-z0-9]+
quotedparam ::= '"' stringliteral '"'
stringliteral ~ [^"]+
rparen ~ ')'

});
say $grammar->show_rules;

for my $input (qw[
    func("foo")
    bar123
    foo(123)
]) {
    my $r = Marpa::R2::Scanless::R->new({
        grammar => $grammar,
        trace_terminals => 1
    });
    $r->read(\$input);
    say Dumper $r->value;
}

答案 1 :(得分:0)

引用字符串:不要忘记排除\&#34;本身来自字符串&#39;

\"([^\"]*)\"

不允许使用某些字符的带引号的字符串(例如,&#39;:&#39;)

\"([^\":]*)\"