简体   繁体   中英

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]

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM