Kit22092 Kit22092 - 4 years ago 115
C# Question

C# Split String without sub string using regex group

The String Like this:

Select(GetName(null),GetID(22),1,GetID(),GetData("T",100),true);


I want to split the string (function).

Return like this:

String MainFunName = "Select()"
String MainFunName_Parameters="GetName(null),GetID(22),1,GetID(),GetData("T",100),true"
int MainFunName_Parameters1_Count = 6;

GetName(null)
GetID(22)
1
GetID()
GetData("T",100)
true


I was try

_str.Substring(_str.IndexOf("(") + _str.Length).Split(',').Count();


It will get 7 not 6, the GetData("T",100) was splited to two part

GetData("T"
100)


I would like to know how to use the regex group to split this string? thanks

Answer Source

You can use it like this:

String str = "Select(GetName(null),GetID(22),1,GetID(),GetData(\"T\",100),true)";
Match result = Regex.Match(str, @"^(\w+)\((\w+(\(.*?\))?,?)*\)$");

string outerMethodName = result.Groups[1].Value;
List<string> arguments = result.Groups[2].Captures.Cast<Capture>().Select(i => i.Value.TrimEnd(',')).ToList();

Console.WriteLine(outerMethodName);

int argumentLength = arguments.Count;
foreach (string argument in arguments)
{
    Console.WriteLine(argument);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download