Home > OS >  Replace everything but the number outside the brackets?
Replace everything but the number outside the brackets?

Time:10-12

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.

CodePudding user response:

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.

CodePudding user response:

You can iterate the input chars and generate a new char array according to the condition.
I don't know about c#, but the Java code should be like the below:

    String input = "12,15,22,(46),78,234,1,89,12,(21,99,66),78,65,63,(343,5)";
    char[] outputChars = new char[input.length()];

    int leftBraketCnt = 0;
    for (int i = 0; i < input.length(); i  ) {
        char c = input.charAt(i);
        if('(' == c) {
            leftBraketCnt  ;
        }
        if(')' == c) {
            leftBraketCnt--;
        }

        if(leftBraketCnt == 0 && c == ',') {
            outputChars[i] = '.';
        }else
            outputChars[i] = c;
    }

    String output = new String(outputChars);
    System.out.println(output);
  • Related