I have the following string:
[A] == [B] * 10 - FUNCTION([C], STRING_EXPRESSION, FUNCTION([D],[C],[E])), FUNCTION([C], [X]), 100
and want to split it by commas that are outside parentheses to this:
[A] == [B] * 10 - FUNCTION([C], STRING_EXPRESSION, FUNCTION([D],[C],[E]))
FUNCTION([C], [X])
100
I was not able to do this alone or using any of the similar answers here.
For example, ,\s*(?!\[^()\]*\))
regular expression works well, but only if not nested parentheses are used, which is my case.
Could anyone tell me how to split the values (using or not regular expression)?
You can use matching instead of splitting:
(?:(?:\((?>[^()]+|\((?<number>)|\)(?<-number>))*(?(number)(?!))\))|[^,])+
See demo
This part - \((?>[^()]+|\((?<number>)|\)(?<-number>))*(?(number)(?!))\)
- matches balanced parentheses, and this - [^,]
- any character but a comma.
See IDEONE demo:
var line = "[A] == [B] * 10 - FUNCTION([C], STRING_EXPRESSION, FUNCTION([D],[C],[E])), FUNCTION([C], [X]), 100";
var matches = Regex.Matches(line, @"(?:(?:\((?>[^()]+|\((?<number>)|\)(?<-number>))*(?(number)(?!))\))|[^,])+");
foreach (Match m in matches)
Console.WriteLine(m.Value.Trim());
Output:
[A] == [B] * 10 - FUNCTION([C], STRING_EXPRESSION, FUNCTION([D],[C],[E]))
FUNCTION([C], [X])
100
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With