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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With