Ale*_*x J 7 .net c# regex recursive-regex
我知道.net中有关于正则表达式递归的几个问题.我可以写一些复杂的正则表达式,但这个递归超出了我,我只是无法写它.
这是最接近我想要的问题.
但它匹配整个字符串,我希望集合中的匹配最好是最里面的匹配,或者按照某种顺序.它还匹配一个开头字符和一个结束字符.我打开和关闭是2个字符,[!和!]
我的输入字符串将是这样的.
[!a='test' b='[!a='innertest' b='innervalue'!]'!]
Run Code Online (Sandbox Code Playgroud)
我需要首先找到最不合适的部分,[!a='innertest' b='innervalue'!],然后通过我的一个表达树来评估它.然后评估包含它的父级.
有人能帮忙吗?
por*_*ges 12
这是一种可能满足您需求的模式:
^\[!((?<n>\w+='\[!)|(?<inner-n>!]')|\w+='(?!\[!)[^']*'| )*!](?!(n))$
Run Code Online (Sandbox Code Playgroud)
它将按顺序为每个项目提供最里面的项目.为了解释我的意思,给出代码:
[!a='test' c='[!x='blah'!]' b='[!a='[!y='innermost'!]' b='innervalue'!]' !]
Run Code Online (Sandbox Code Playgroud)
它将提供以下匹配(在"内部"组的捕获集合中):
x='blag'
y='innermost'
a='[!y='innermost'!]' b='innervalue'
Run Code Online (Sandbox Code Playgroud)
因此,对于每个x=y项目[! .. !],它将从最里面向外按顺序给出匹配.
如果您还想捕获整个表达式,可以像这样修改它:
^(?<n>\[!)((?<n>\w+='\[!)|(?<inner-n>!]')|\w+='(?!\[!)[^']*'| )*(?<inner-n>!])(?!(n))$
Run Code Online (Sandbox Code Playgroud)
赠送:
x='blag'
y='innermost'
a='[!y='innermost'!]' b='innervalue'
a='test' c='[!x='blag'!]' b='[!a='[!y='innermost'!]' b='innervalue'!]'
Run Code Online (Sandbox Code Playgroud)
并解释正则表达式:
^ # 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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3956 次 |
| 最近记录: |