gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 20:05:40 26 4
gpt4 key购买 nike

我知道有几个关于 .net 中正则表达式递归的问题。我可以编写稍微复杂的正则表达式,但这种递归超出了我的能力范围,我就是写不出来。

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

first question, second question .

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

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

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

我需要先找到内部测试部分 [!a='innertest' b='innervalue'!],然后通过我的一个表达式树对其求值。然后评估包含它的父级。

有人可以帮忙吗?

最佳答案

下面是一个可能满足您需求的模式:

^\[!((?<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'

因此,对于 [! .. !],它会按照从最里到外的顺序给出匹配。

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

^(?<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

关于c# - 使用正则表达式 c# 递归地获取内部模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9813751/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com