正则表达式用定界符拆分,同时保留定界符
Regex Split with Delimiters while keeping delimiters
我正在尝试将带有分隔符的字符串拆分为数组,同时保留分隔符。
我得到的字符串是:“2+37/4+26”。
我希望数组为:[2,+,37,/,4,+,26]
您可以使用 lookarounds 拆分:
String[] tok = input.split("(?<=[+*/-])|(?=[+*/-])");
解释:
(?<=[+*/-]) # when preceding character is one of 4 arithmetic operators
| # regex alternation
(?=[+*/-]) # when following character is one of 4 arithmetic operators
我正在尝试将带有分隔符的字符串拆分为数组,同时保留分隔符。
我得到的字符串是:“2+37/4+26”。
我希望数组为:[2,+,37,/,4,+,26]
您可以使用 lookarounds 拆分:
String[] tok = input.split("(?<=[+*/-])|(?=[+*/-])");
解释:
(?<=[+*/-]) # when preceding character is one of 4 arithmetic operators
| # regex alternation
(?=[+*/-]) # when following character is one of 4 arithmetic operators