user2715533
user2715533

Reputation: 27

Nested PCRE Regex Issue

I have a custom template engine.

It catch this :

@function(argument1 argument2 ...)
@get(param:name)
@get(param:@get(sub:name))

And this :

@function(argument1 argument2 ...)

    Some stuff @with(nested:tag)

    @foreach(arguments as value)
        More stuff : @get(value)
    @/foreach

    @function(other:args)
        Same function name (nested)
    @/function

@/function

With this pattern (PCRE / PHP) :

#

@ ([\w]+) \(

( (?: [^@\)] | (?R) )+ )

\)

(?:
    ( (?> (?-2) ) )

    @/\\1
)?

#xms

This regex catch almost all results. But when i have more nested (or not) tags, then it catch nothing. For example, when i do 2 nested @foreach(var:name) ... @/foreach then the regex will fail depending of the tag content spaces.

Upvotes: 2

Views: 118

Answers (1)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89547

Using named subpatterns is sometimes more clear. I suggest you to use this:

~
@(?<com>\w+)                 # command name
\s*                          # possible white characters before args
(?: \( (?<args>[^)]*) \) )?+ # eventual parameters
(?:
    (?<content>(?:[^@]+|(?R))*+) # content (maybe empty)
    @/\g{com}                    # close the command
)?+                          # optional
~

If you need to allow commands inside arguments, you can replace (?<args>[^)]*) with (?<args>(?:[^@)]+|(?=@)(?R))*+)

But a better way when you are trying to describe a language is to use the (?(DEFINE)...) syntax to describe elements first, before the main pattern, example:

$pattern = <<<'EOD'
~
(?(DEFINE)
    (?<command_name> \w+ )
    (?<inline_command> @ \g<command_name> \s* \g<params>? )
    (?<multil_command> @ (\g<command_name>) \s* \g<params>? \g<content> @/ \g{-1} )
    (?<command> \g<multil_command> | \g<inline_command> )

    (?<other> [^@()]+ ) 
    (?<param> \g<other> | \g<command> )
    (?<params> \( \s* \g<param> (?: \s+ \g<param> )* \s* \) )

    (?<content> (?: \g<other> | \g<command> )* )
)
# main pattern
\g<command>
~x
EOD;

With this kind of syntax, if you want to extract elements at the ground level, you only need to change the main pattern to: @(?<com> \g<command_name> ) \s* (?<args>\g<params> )? (?: (?<con> \g<content> ) @/ \g{com} )? (NB: To obtain other levels, put it inside a lookahead)

Upvotes: 1

Related Questions