3

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]

th3r1singking
  • 119
  • 1
  • 3
  • 13
  • Does this answer your question? [How to split a string, but also keep the delimiters?](/q/2206378/90527) – outis Aug 17 '22 at 20:37

1 Answers1

3

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
anubhava
  • 761,203
  • 64
  • 569
  • 643