Ruby 正则表达式中递归嵌套匹配的花括号对 [英] Recursive nested matching pairs of curly braces in Ruby regex

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

问题描述

我有以下字符串:

The {quick} brown fox {jumps {over {deep} the} {sfsdf0} lazy} dog {sdfsdf1 {sdfsdf2}

和 PHP 正则表达式:

And PHP Regular Expression:

/(?=\{((?:[^{}]+|\{(?1)\})+)\})/g

它产生以下匹配:

[5-10]  `quick`
[23-60] `jumps {over {deep} the} {sfsdf} lazy`
[30-45] `over {deep} the`
[36-40] `deep`
[48-54] `sfsdf0`
[76-83] `sdfsdf2`

请参阅:http://regex101.com/r/fD3iZ2.

我正在尝试在 Ruby 中实现等效的工作,但是我遇到了 (?1) 问题……导致了 undefined group option 错误:

I'm trying to get the equivalent working in Ruby, but I'm having a problem with (?1)… resulting in an undefined group option error:

str = "The {quick} brown fox {jumps {over {deep} the} {sfsdf} lazy} dog {sdfsdf {sdfsdf}"
str.scan /(?=\{((?:[^{}]+|\{(?1)\})+)\})/

SyntaxError: undefined group option: /(?=\{((?:[^{}]+|\{(?1)\})+)\})/

参见:http://fiddle.re/n6w4n.

巧合的是,我在 Javascript 和 Python 中遇到了同样的错误.

Coincidently, I get the same sort of error in Javascript and Python.

我的正则表达式 foo 今天几乎用完了,非常感谢任何帮助.

My regex foo is nearly exhausted today, any help very much appreciated.

推荐答案

Ruby 使用不同的递归语法:\g<1> 替换 (?1).所以试试

Ruby uses a different syntax for recursion: \g<1> replaces (?1). So try

(?=\{((?:[^{}]++|\{\g<1>\})++)\})

我还使量词具有所有格,以避免在大括号不平衡的情况下过度回溯.

I also made the quantifiers possessive to avoid excessive backtracking in case of unbalanced braces.

irb(main):003:0> result = str.scan(/(?=\{((?:[^{}]++|\{\g<1>\})++)\})/)
=> [["quick"], ["jumps {over {deep} the} {sfsdf} lazy"], ["over {deep} the"], 
["deep"], ["sfsdf"], ["sdfsdf"]]

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

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