如何用Regex验证中缀表达式:确保操作数被操作符分隔
Great observation—your original regex handles the basic structure of infix expressions, but it doesn't enforce the critical rule that operands must always be separated by operators (and vice versa, no consecutive operators). The fix is to force an alternating operand-operator-operand pattern instead of allowing arbitrary mixes of operands/operators in the middle.
The Updated Regex
^[a-zA-Z0-9_]+( [\+\-\/\*] [a-zA-Z0-9_]+)*$
Breakdown of How This Works
Let's walk through the pattern to see how it solves your problem:
^[a-zA-Z0-9_]+: Starts with a valid operand (matches your original operand definition: letters, numbers, underscores, one or more characters)( [\+\-\/\*] [a-zA-Z0-9_]+)*: This is the key improvement. It defines a repeatable unit that must be:- A single space
- A valid operator (
+,-,/,*) - Another single space
- A valid operand
The*means this unit can appear 0 or more times—so it supports single-operand expressions (likemyVar) as well as multi-part expressions (likex + y * z)
$: Ensures we don't have any trailing characters (like an unpaired operator at the end)
Why This Fixes Your Original Gap
Your original regex allowed inserting standalone operands or operators in the middle (e.g., a b + c or a + - b). This new pattern eliminates those invalid cases by requiring every subsequent element after the first operand to be a complete operator-operand pair. This guarantees:
- No consecutive operands (they're always separated by an operator)
- No consecutive operators (each operator is immediately followed by an operand)
- Operators can't appear at the start or end of the expression
Test Cases
Valid Matches
singleOperanda + buser_input * 42 - total
Invalid Matches (Rejected by the Regex)
a b + c(consecutive operands)a + - b(consecutive operators)+ startWithOperator(operator at start)endWithOperator +(operator at end)noSpaces+here(missing required spaces)
Optional: If You Need Parentheses
Note: This regex doesn't handle parentheses (e.g., (a + b) * c) since your original question didn't mention them. If you need to support parentheses, we'd need to extend the pattern to handle nested groups, but that's a more complex problem. For your stated requirements, the above regex is perfect.
内容的提问来源于stack exchange,提问作者androlama

