我需要编写正则表达式来捕获特殊类型的名称类型的通用参数(也可以是通用的),如下所示:
System.Action[Int32,Dictionary[Int32,Int32],Int32]
让我们假设类型名称为[\w.]+
and参数为,[\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+(?:\[[^][]*])?))*
请参阅regex演示。
细节:
\w+(?:\.\w+)*
-匹配1+个单词字符,然后再匹配.
+ 1+个单词字符1次或更多次\[
-文字 [
(?:,?(?<res>\w+(?:\[[^][]*])?))*
-0个或多个序列:
,?
-可选的逗号(?<res>\w+(?:\[[^][]*])?)
-组“ res”捕获:
\w+
-一个或多个单词字符(也许您想[\w.]+
)(?:\[[^][]*])?
- 1或0(变化?
到*
匹配1个或多个)的一个序列[
,0+字符以外[
和]
,和封闭]
。以下是一个C#演示:
var line = "System.Action[Int32,Dictionary[Int32,Int32],Int32]";
var pattern = @"\w+(?:\.\w+)*\[(?:,?(?<res>\w+(?:\[[^][]*])?))*";
var result = Regex.Matches(line, pattern)
.Cast<Match>()
.SelectMany(x => x.Groups["res"].Captures.Cast<Capture>()
.Select(t => t.Value))
.ToList();
foreach (var s in result) // DEMO
Console.WriteLine(s);
更新:要解决未知深度[...]
子字符串,请使用
\w+(?:\.\w+)*\[(?:\s*,?\s*(?<res>\w+(?:\[(?>[^][]+|(?<o>\[)|(?<-o>]))*(?(o)(?!))])?))*
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句