PC Luddite PC Luddite - 1 year ago 70
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:


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

The program outputs this:

Match: lorem$
Variable: lorem$

Match: @sit
Variable: @sit

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 Source

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:


To this:


See test

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download