PC Luddite PC Luddite - 3 months ago 9
C# Question

Matching varName$[index] and @varName[index] in C# (regular expression help)

In this string:

"lorem$ dolor @sit ipsum amet$[consectetuer$[5]] @adipiscing[@elit[3]]"


I want to match the following:


lorem$
@sit
amet$[consectetur$[5]]
@adipiscing[@elit[3]]



I've almost got the expression down, but for some reason I can't quite get it. This is my tester program right now. Here's what I have so far:

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();
}


The program outputs this:


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



It's almost correct! The last two matches are just missing the last bracket. What am I doing wrong?

Answer

You're only set up to capture one of the ]'s

You need to add another terminating ] to the Index named group to capture it

Change this:

(?<Variable>([\w\d]+\$|\@[\w\d]+))(\s*\[(?<Index>.*?)\]|[\W\D\s])

To this:

(?<Variable>([\w\d]+\$|\@[\w\d]+))(\s*\[(?<Index>.*?\]+)\]|[\W\D\s])

See test