Java中按变量符号拆分数学函数的正确正则表达式
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 the10).
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

