如何用Java正则表达式匹配合法的算术运算序列?
Fixing Your Regex for the Smart Calculator Project
Hey there! Let's break down why your current regex isn't working consistently for valid arithmetic inputs like 1 + 1 + 1, and fix it up to match exactly what you need for your project.
The Problem with Your Current Regex
Your regex (\s*[0-9]+\s*[\+\-\*\/]+\s*[0-9]+\s*){1,} has two key issues:
- Incorrect grouping logic: The regex is designed to match chunks of
[number][operator][number]and repeat that. But when you have a longer expression like1 + 1 + 1, the first chunk matches1 + 1, leaving+ 1leftover — which can't match the chunk pattern (since it starts with an operator, not a number). That's why1 + 1 + 1fails, while1 + 12 + 1might accidentally work due to unreliable regex engine backtracking. - Unintended multiple operators: The
[\+\-\*\/]+part allows consecutive operators like2 ++ 3or5 -- 2, which are invalid inputs for your calculator.
The Corrected Regex
Here's a regex that will properly match valid arithmetic expressions (single numbers or chains like 2 + 2 - 3) and reject invalid ones like 2 + 2 -:
^\s*\d+\s*(?:[+*/-]\s*\d+\s*)*$
Let's break down what each part does:
^and$: These anchor the regex to the start and end of the input string. This ensures we don't match partial inputs (like the first half of2 + 2 -).\s*\d+\s*: Matches a number (\d+) with any amount of whitespace (\s*) before and after it — handling the starting number of your expression.(?:[+*/-]\s*\d+\s*)*: A non-capturing group (the?:makes it non-capturing for efficiency) that matches:- A single valid operator (
[+*/-]— we put-at the end of the character class to avoid it being interpreted as a range character) - Followed by whitespace, a number, and more whitespace
- The
*means this group can repeat 0 or more times — so it handles expressions with multiple operators, or even just a single number if needed.
- A single valid operator (
Adjustments for Edge Cases
- If you don't want to allow single-number inputs (e.g., you require at least one operator), change the
*at the end to a+:^\s*\d+\s*(?:[+*/-]\s*\d+\s*)+$ - If you need to support negative numbers (like
-5 + 3), you'd need to tweak the regex to handle optional leading-on numbers, but that's an extra step if your project requires it.
Testing Your Examples
Let's verify this regex against your test cases:
1 + 1: ✅ Matches successfully1 + 1 + 1: ✅ Matches successfully (no more failure!)1 + 12 + 1: ✅ Matches successfully2 + 2 -: ❌ Fails to match (perfect, since it's invalid)
内容的提问来源于stack exchange,提问作者zvz
相关产品推荐
相关产品推荐

