我正在尝试使用分隔符将字符串拆分为数组,同时保留分隔符。 我有的字符串是:"2+37/4+26"。我希望数组是:
[2,+,37,/,4,+,26]
。您可以使用正向/反向预查来进行拆分:
String[] tok = input.split("(?<=[+*/-])|(?=[+*/-])");
Explanation:
(?<=[+*/-]) # when preceding character is one of 4 arithmetic operators
| # regex alternation
(?=[+*/-]) # when following character is one of 4 arithmetic operators
String[] tok = input.split("(?<=[()+*/-])|(?=[()+*/-])");
- anubhava(?<=...)
是正向后查找,而 (?=...)
是正向前查找。 - anubhava