0

I need a regex that substitutes a string by looking at their commas.
For example the string:

str1 = "a,b,12,func(a,b),8,bob,func(1,2))"

should be transformed as following:

str1_transformed = "a;b;12;func(a,b);8;bob;func(1,2))"

I cannot substitute every "," with a ";" because it will look like:

str1_wrong = "a;b;12;func(a;b);8;bob;func(1;2))"

How can I deal with it? I looked at the following threads without success:
How can I Split(',') a string while ignore commas in between quotes?
Regular Expression for Comma Based Splitting Ignoring Commas inside Quotes

Davide
  • 1,931
  • 2
  • 19
  • 39
  • Which programming language are you coding it? I've guessed it is C#, if I'm wrong. please retag it. – Dragonthoughts May 20 '18 at 19:20
  • @Dragonthoughts I'm using scala, but regex should work indifferently by the program language – Davide May 20 '18 at 19:22
  • 1
    I agree that there should be no difference, but the actuality is that different languages and libraries implement regex differently. – Dragonthoughts May 20 '18 at 19:24
  • 3
    You may try `,(?![^()]*\))` to select commas that are outside of brackets. See demo here https://regex101.com/r/8X8TWH/1 – revo May 20 '18 at 19:27
  • @revo Thanks. This work great. Now I try to understand it. Thank you so much – Davide May 20 '18 at 19:29

1 Answers1

3

If you know that you won't have unbalanced or escaped brackets below regex works well:

,(?![^()]*\))

Breakdown:

  • , Match a comma
  • (?! Start of negative lookahead
    • [^()]*\) That means, recent matched comma shouldn't follow a closing bracket without matching opening bracket
  • ) End of lookahead

C# code:

Regex regex = new Regex(@",(?![^()]*\))");
string result = regex.Replace(@"a,b,12,func(a,b),8,bob,func(1,2))", @";");
revo
  • 47,783
  • 14
  • 74
  • 117