th3r1singking
th3r1singking

Reputation: 131

Regex Split with Delimiters while keeping delimiters

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]

Upvotes: 3

Views: 870

Answers (1)

anubhava
anubhava

Reputation: 784958

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

Upvotes: 3

Related Questions