Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Splitting values by commas that are outside parentheses?

Tags:

c#

.net

regex

split

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

like image 809
gotqn Avatar asked Aug 10 '15 12:08

gotqn


Video Answer


1 Answers

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.

enter image description here

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
like image 188
Wiktor Stribiżew Avatar answered Sep 29 '22 00:09

Wiktor Stribiżew