在此字符串中:
"lorem$ dolor @sit ipsum amet$[consectetuer$[5]] @adipiscing[@elit[3]]"
我要符合以下条件:
lorem$
@sit
amet$[consectetur$[5]]
@adipiscing[@elit[3]]
我的表情几乎差一点了,但是由于某种原因,我不太理解。这是我现在的测试程序。这是我到目前为止的内容:
Regex varEx = new Regex(@"(?<Variable>([\w\d]+\$|\@[\w\d]+))(\s*\[(?<Index>.*?)\]|[\W\D\s])");
string test = "lorem$ dolor @sit ipsum amet$[consectetuer$[5]] @adipiscing[@elit[3]]";
foreach (Match m in varEx.Matches(test)) {
Console.WriteLine("{0,10} {1}", "Match:", m.Value);
Console.WriteLine("{0,10} {1}", "Variable:", m.Groups["Variable"].Value);
Console.WriteLine("{0,10} {1}", "Index:", m.Groups["Index"].Value);
Console.WriteLine();
}
程序输出以下内容:
Match: lorem$
Variable: lorem$
Index:
Match: @sit
Variable: @sit
Index:
Match: amet$[consectetuer$[5]
Variable: amet$
Index: consectetuer$[5
Match: @adipiscing[@elit[3]
Variable: @adipiscing
Index: @elit[3
几乎是对的!最后两场比赛只剩下最后一位。我究竟做错了什么?
最佳答案
您只需设置为捕获]
的其中一个
您需要向]
命名组中添加另一个终止Index
来捕获它
更改此:
(?<Variable>([\w\d]+\$|\@[\w\d]+))(\s*\[(?<Index>.*?)\]|[\W\D\s])
对此:
(?<Variable>([\w\d]+\$|\@[\w\d]+))(\s*\[(?<Index>.*?\]+)\]|[\W\D\s])
见test
关于c# - 在C#中匹配varName $ [index]和@varName [index](正则表达式帮助),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27515643/