Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a string representing a recursive data structure using Perl regular expressions?

Tags:

regex

tree

perl

I wonder what methods are in Perl for traversing a recursive structure (e.g. binary tree) which is given as a string.

More concretely:

Here is a tree, for simplicity is parse tree and very short. imagine it is string without fancy tabbing and spaces.

tree(Sentence, 
  tree(NounPhrase,
    leaf(Determiner, "a"),
    leaf(Noun, "man", "singular")
  ), 
  tree(VerbPhrase,
    leaf(Verb, "walks", "present", "3rd person")
  )
)

Now I want to access two direct child nodes of the root, but I cannot do this with regular expressions simply.

m/tree \( \w+ , (group1) , (group2) \) /x

I would like to capture group1 and group2 correctly, i.e. group1 and group2 having even number of opening and closing parentheses.

It seems quite complicated task and wonder what is the common/simplest solution to it?

For example, prolog will easily digest this task.

like image 607
Fibo Kowalsky Avatar asked Aug 16 '26 00:08

Fibo Kowalsky


1 Answers

I would try by creating 2 functions: sub tree{} and sub leaf{}

each of them would return a tagged term as a string, for example leaf(Determiner, "a") would return <Determiner>a</Determiner>

then simply execute the file you want to process. The output would be a DOM like structure which you can parse with any DOM parser like XML::DOM for example

like image 68
Tudor Constantin Avatar answered Aug 17 '26 16:08

Tudor Constantin



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!