I am trying to split a string with delimiters into an array while keeping the delimiters as well.
The string that I have is: "2+37/4+26".
I want the array to be: [2,+,37,/,4,+,26]
You can split using lookarounds:
String[] tok = input.split("(?<=[+*/-])|(?=[+*/-])");
RegEx Demo
Explanation:
(?<=[+*/-]) # when preceding character is one of 4 arithmetic operators
| # regex alternation
(?=[+*/-]) # when following character is one of 4 arithmetic operators
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