Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to split string with round brackets in it?

Got a String:

String s = "1+2*(30+4/2-(1+2))*2+1";

Got method to split a string:

    public void convertString(String s) {
        String[] arr = s.split("(?<=[\\d.])(?=[^\\d.])|(?<=[^\\d.])(?=[\\d.])");
}

problem is:

    Output:
    [1, +, 2, *(, 30, +, 4, /, 2, -(, 1, +, 2, ))*, 2, +, 1] 
    //here round brackets store in the same cell with next symbol or prev symbol   *(,  ))*,

expected output:

[1, +, 2, *, (, 30, +, 4, /, 2, -, (, 1, +, 2, ), ), *, 2, +, 1]
// here round brackets store in a separate arr cells

I need to store round brackets in the separate array cells.

How to achieve it?

like image 220
Dartweiler Avatar asked Dec 06 '25 18:12

Dartweiler


1 Answers

Your regex literally splits at any location that goes from non-digit to digit, or vice versa. It explicitly does not split between non-digits.

So give your current method, the fix would be

public void convertString(String s) {
    String[] arr = s.split("(?<=[\\d.])(?=[^\\d.])|(?<=[^\\d.])(?=[^\\d.])|(?<=[^\\d.])(?=[\\d.])");
}

That said, it's probably better ways of doing this. A simple regex match, where the expression is either a single-non-digit, or an eager group of digits, will already be easier than this.

like image 100
Joeri Hendrickx Avatar answered Dec 08 '25 06:12

Joeri Hendrickx



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!