Search code examples
c#regexregexp-replace

Replace everything but the number outside the brackets?


Input String:

string input="12,15,22,(46),78,234,1,89,12,(21,99,66),78,65,63,(343,5)";

Replace comma with dot but only applicable for outside the brackets. Expected Output:

string ExpectedOutput="12.15.22.(46).78.234.1.89.12.(21,99,66).75.65.63.(343,5)";

I tired so far

\d*(\(\d*?\))\d*

but it is not working as expected.


Solution

  • You can use this regex:

    new Regex(@"(?<=\d|\))(?<!\([\d,]+),");
    

    and replace with a dot (.).

    Explanation:

    (?<=\d|\)) - look behind for a digit OR end parentes

    (?<!\([\d,]+) - negative look behind for start parentes followed by one or more digits OR commas

    , - match a comma ,

    Now simply replace with a dot ..

    I have made a test case here: NetRegexBuilder.