带有递归表达式的正则表达式匹配嵌套的大括号? [英] Regex with recursive expression to match nested braces?

查看:67
本文介绍了带有递归表达式的正则表达式匹配嵌套的大括号?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试匹配像 sp { ...{...}... } 这样的文本,其中允许大括号嵌套.这是我目前所拥有的:

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/
(                   #save $1
    sp\s+           #start Soar production
    (               #save $2
        \{          #opening brace
        [^{}]*      #anything but braces
        \}          #closing brace  
        | (?1)      #or nested braces
    )+              #0 or more
)
/x;

我只是无法让它匹配以下文本:sp { { word } }.谁能看出我的正则表达式有什么问题?

I just cannot get it to match the following text: sp { { word } }. Can anyone see what is wrong with my regex?

推荐答案

问题很多.递归位应该是:

There are numerous problems. The recursive bit should be:

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

一起:

my $regex = qr/
   sp\s+
   \{
      (
         (?: \{ (?-1) \}
         |   [^{}]++
         )*
      )
   \}
/x;

print "$1\n" if 'sp { { word } }' =~ /($regex)/;

这篇关于带有递归表达式的正则表达式匹配嵌套的大括号?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆