Separating values ​​with commas that are outside parentheses?

I have the following line:

[A] == [B] * 10 - FUNCTION([C], STRING_EXPRESSION, FUNCTION([D],[C],[E])), FUNCTION([C], [X]), 100 

and you want to break it with commas outside the parentheses:

  • [A] == [B] * 10 - FUNCTION([C], STRING_EXPRESSION, FUNCTION([D],[C],[E]))
  • FUNCTION([C], [X])
  • 100

I could not do this alone or use any similar answers here.

For example, the regex ,\s*(?!\[^()\]*\)) Works well, but only if the parentheses are not enclosed, this is my case.

Can someone tell me how to separate the values ​​(using or not a regular expression)?

+6
source share
2 answers

You can use matching instead of splitting:

 (?:(?:\((?>[^()]+|\((?<number>)|\)(?<-number>))*(?(number)(?!))\))|[^,])+ 

See demo

This part - \((?>[^()]+|\((?<number>)|\)(?<-number>))*(?(number)(?!))\) - corresponds to balanced brackets, and this is [^,] - any character, but a comma.

enter image description here

See the 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 
+4
source
 string s = "[A] == [B] * 10 - FUNCTION([C], STRING_EXPRESSION, FUNCTION([D], [C],[E])), FUNCTION([C], [X]), 100"; List<string> splitted = new List<string>(); int beginPos = 0; for (int i=1; i < s.Length; i++) { if (s[i] == ',' && s[i-1] == ')')// && i!=beginPos) { splitted.Add(s.Substring(beginPos, i-beginPos)); i++; beginPos = i; } } if(beginPos < s.Length) splitted.Add(s.Substring(beginPos, s.Length-beginPos)); 
-1
source

All Articles