【发布时间】:2016-12-07 19:32:27
【问题描述】:
我需要编写正则表达式,以特殊符号捕获类型名称的通用参数(也可以是通用的),如下所示:
System.Action[Int32,Dictionary[Int32,Int32],Int32]
假设类型名称为[\w.]+,参数为[\w.,\[\]]+
所以我只需要抓住Int32、Dictionary[Int32,Int32] 和Int32
如果平衡组堆栈为空,我基本上需要采取一些措施,但我不太明白如何。
UPD
下面的答案帮助我快速解决了问题(但没有适当的验证并且深度限制 = 1),但我已经设法通过组平衡做到了:
^[\w.]+ #Type name
\[(?<delim>) #Opening bracet and first delimiter
[\w.]+ #Minimal content
(
[\w.]+
((?(open)|(?<param-delim>)),(?(open)|(?<delim>)))* #Cutting param if balanced before comma and placing delimiter
((?<open>\[))* #Counting [
((?<-open>\]))* #Counting ]
)*
(?(open)|(?<param-delim>))\] #Cutting last param if balanced
(?(open)(?!) #Checking balance
)$
UPD2(上次优化)
^[\w.]+
\[(?<delim>)
[\w.]+
(?:
(?:(?(open)|(?<param-delim>)),(?(open)|(?<delim>))[\w.]+)?
(?:(?<open>\[)[\w.]+)?
(?:(?<-open>\]))*
)*
(?(open)|(?<param-delim>))\]
(?(open)(?!)
)$
【问题讨论】:
-
试试
\w+(?:\.\w+)*\[(?:,?(?<res>\w+(?:\[[^][]*])?))*。${res}捕获将包含这些值。如果您有 1 个嵌套级别[...],则此处不需要任何平衡组。我什至不确定你需要\w+(?:\.\w+)*
标签: c# .net regex balancing-groups