Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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]

like image 554
th3r1singking Avatar asked Nov 30 '25 16:11

th3r1singking


1 Answers

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
like image 145
anubhava Avatar answered Dec 03 '25 06:12

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!