Regex with recursive expression to match nested braces?

后端 未结 2 1273
执笔经年
执笔经年 2021-01-18 05:25

I\'m trying to match text like sp { ...{...}... }, where the curly braces are allowed to nest. This is what I have so far:

my $regex = qr/
(             


        
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-01-18 05:36

    There are numerous problems. The recursive bit should be:

    (
       (?: \{ (?-1) \}
       |   [^{}]+
       )*
    )
    

    All together:

    my $regex = qr/
       sp\s+
       \{
          (
             (?: \{ (?-1) \}
             |   [^{}]++
             )*
          )
       \}
    /x;
    
    print "$1\n" if 'sp { { word } }' =~ /($regex)/;
    

提交回复
热议问题