You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Java中按变量符号拆分数学函数的正确正则表达式

Fixing the Math Function Split to Keep Operators

Got it, let's tackle this problem! The issue with your current split("=|-|\\+") is that it removes the separators (-, +, =) entirely from the result array—hence why you're missing those symbols in your output.

To keep the operators attached to their respective terms (and include the = with the right-hand side value), you need a regex that splits the string before each operator without consuming the operator itself. Here's how to do it:

Correct Regex & Code Example

Use a positive lookahead assertion to target positions where an operator (-, +, =) follows. This is a zero-width match, so it won't remove the operator from the final result:

String function = "x-5y+3z=10";
String[] splitResult = function.split("(?=[-+=])");
// Result: [x, -5y, +3z, =10]

How This Works

  • (?=[-+=]) is a positive lookahead: it matches a position in the string where the next character is either -, +, or =.
  • Since it's a zero-width assertion, the split happens at that position without deleting the operator. This ensures each operator stays attached to the term that comes after it (including the = with the 10).

This even handles edge cases like leading operators—for example, if your input was "-x+5y=7", the split would give you ["-x", "+5y", "=7"], which is exactly what you'd want.

内容的提问来源于stack exchange,提问作者Mohamed Essam

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:05:26