Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string with multiple delimiter including delimiters

I would like to split a string using multiple character delimiters, but I also want to store delimiters. My delimiters are ()+-*/

So for example, if I had a string

26+78(12*23)-16

I want to get

26

+

78

(

12

*

23

)

-

16

each line as a separate array element.

I think you can not use split function to achieve this. However, my trial with string-tokenizer also failed. How can I achieve this?

like image 541
Ersel Aker Avatar asked Jan 15 '23 18:01

Ersel Aker


1 Answers

I wouldn't answer if it wasn't saturday night here:

    String s1 = "26+78(12*23)-16";
    for(String s: s1.split("(?<=[()+*/-])|(?=[()+*/-])")){
        System.out.println(">> " + s);
    }

gives:

>> 26
>> +
>> 78
>> (
>> 12
>> *
>> 23
>> )
>> -
>> 16
like image 83
Nishant Avatar answered Jan 17 '23 06:01

Nishant