这是一个可能满足您需求的模式:
^\[!((?<n>\w+='\[!)|(?<inner-n>!]')|\w+='(?!\[!)[^']*'| )*!](?!(n))$
它将按顺序给出每个项目的最里面的项目。为了解释我的意思,给定代码:
[!a='test' c='[!x='blah'!]' b='[!a='[!y='innermost'!]' b='innervalue'!]' !]
它将给出以下匹配项(在组“inner”的捕获集合中):
x='blag'
y='innermost'
a='[!y='innermost'!]' b='innervalue'
因此,对于 中的每个x=y
项目[! .. !]
,它将按从最里面向外的顺序给出匹配项。
如果您还希望捕获整体表达式,您可以像这样修改它:
^(?<n>\[!)((?<n>\w+='\[!)|(?<inner-n>!]')|\w+='(?!\[!)[^']*'| )*(?<inner-n>!])(?!(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 ...
(?<n>\w+='\[!)| # a complex x='[! .. !]' containing a nested [! .. !] - push this onto the stack 'n'
(?<inner-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