Perl Regexp Extract string from nested brackets

我的梦境 提交于 2019-12-25 19:46:13

问题


I am trying to extract some information from a file that has the following content:

field {
    a:"bb"
    c:"dd"
    field_param {
        x:"xx"
        y:"yy"
    }
    other_param {
        z:"ee"
    }
    abc_param {
        x: { abc: "value"; cfg:"value"}
        ze: "value"
    }
}

field {
    a:"bb"
    c:"dd"
    field_param {
        x:"xx"
        y:"yy"
    }
    others_param {
        z:"ee"
    }
}

There are more fields like above, in a text file. Not all the fields are the same format, some have different params.

I am trying to extract for each field, to consider it as object with variables and values. The problem is the nested {} I do not know how to extract the values between {} after splitting all the file in fields. I am taking than, field by field but it does not work to extract the things that are between brackets, if I want to do it recursively.

Until now I did something like:

 open(FILE,"myfile.txt")
    while(<FILE>)
    {
    $text .=$_;
    }
    close(FILE)
    my @fields= split /fields/,$text;
    for my $field(@fields)
    {
    my($extracted,$remainder)=extracted_bracketed($field,'{}');
    }

But this extracts only what is in field. I want to do it somehow recursive.

Anybody has any idea?


回答1:


You need to write a parser, and it sounds like you know nothing about parsing. This language is not all dissimilar to JSON, so I recommend you copy JSON::PP and adapt it to your language.

Alternatively, use a parser builder such as Marpa.



来源:https://stackoverflow.com/questions/33939742/perl-regexp-extract-string-from-nested-brackets

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