3

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?

Dartweiler
  • 85
  • 8

2 Answers2

3

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.

Joeri Hendrickx
  • 16,947
  • 4
  • 41
  • 53
0

don't include brackets in your regex, only take out the specific punctuation which you don't want. you can create an array and use a loop to put the numbers into the array. https://regex101.com/r/tHjoYn/1/ - here you can test for the regex you want.

Gil Caplan
  • 64
  • 8