使用正则表达式c递归获取内部模式

我知道.net中有关于正则表达式递归的几个问题。 我可以编写一些复杂的正则表达式,但这种递归超出了我,我只是无法编写它。

这是最接近我想要的问题。

第一个问题, 第二个问题 。

但它匹配整个字符串,我希望集合中的匹配最好是最里面的匹配,或者按照某种顺序。 它还匹配一个开头字符和一个结束字符。 我打开和关闭是2个字符,[! 和!]

我的输入字符串将是这样的。

[!a='test' b='[!a='innertest' b='innervalue'!]'!] 

我需要首先找到最新的部分, [!a='innertest' b='innervalue'!],然后通过我的一个表达式树来评估它。 然后评估包含它的父母。

有人能帮忙吗?

这是一种可能满足您需求的模式:

 ^\[!((?\w+='\[!)|(?!]')|\w+='(?!\[!)[^']*'| )*!](?!(n))$ 

它将按顺序为每个项目提供最里面的项目。 为了解释我的意思,给出代码:

 [!a='test' c='[!x='blah'!]' b='[!a='[!y='innermost'!]' b='innervalue'!]' !] 

它将给出以下匹配(在“内部”组的捕获集合中):

 x='blag' y='innermost' a='[!y='innermost'!]' b='innervalue' 

所以,对于[! .. !]中的每个x=y项目[! .. !] [! .. !] ,它将从最里面向外按顺序给出比赛。

如果您还想捕获整个表达式,可以像这样修改它:

 ^(?\[!)((?\w+='\[!)|(?!]')|\w+='(?!\[!)[^']*'| )*(?!])(?!(n))$ 

赠送:

 x='blag' y='innermost' a='[!y='innermost'!]' b='innervalue' a='test' c='[!x='blag'!]' b='[!a='[!y='innermost'!]' b='innervalue'!]' 

并解释正则表达式:

 ^ # start of string \[! # start of overall [! .. !] ( # either ... (?\w+='\[!)| # a complex x='[! .. !]' containing a nested [! .. !] - push this onto the stack 'n' (?!]')| # end of a nested [! .. !] - pop stack 'n', and capture the contents into 'inner' \w+='(?!\[!)[^']*'| # a simple x='asdf' with no nested [! .. !] ) # or a space * # as many times as you want !] # the end of the overall [! .. !] (?!(n)) # assert that the 'n' stack is empty, no mismatched [! .. !] $ # end of string