正则表达式拆分与分隔符同时保持分隔符

时间:2015-03-26 17:42:36

标签: java regex delimiter

我正在尝试将带分隔符的字符串拆分为数组,同时保留分隔符。

我拥有的字符串是:“2 + 37/4 + 26”。

我希望数组为:[2,+,37,/,4,+,26]

1 个答案:

答案 0 :(得分:3)

您可以使用lookarounds进行拆分:

String[] tok = input.split("(?<=[+*/-])|(?=[+*/-])");

RegEx Demo

<强>解释

(?<=[+*/-])  # when preceding character is one of 4 arithmetic operators
|            # regex alternation
(?=[+*/-])   # when following character is one of 4 arithmetic operators
相关问题