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

如何用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 like 1 + 1 + 1, the first chunk matches 1 + 1, leaving + 1 leftover — which can't match the chunk pattern (since it starts with an operator, not a number). That's why 1 + 1 + 1 fails, while 1 + 12 + 1 might accidentally work due to unreliable regex engine backtracking.
  • Unintended multiple operators: The [\+\-\*\/]+ part allows consecutive operators like 2 ++ 3 or 5 -- 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 of 2 + 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.

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 successfully
  • 1 + 1 + 1: ✅ Matches successfully (no more failure!)
  • 1 + 12 + 1: ✅ Matches successfully
  • 2 + 2 -: ❌ Fails to match (perfect, since it's invalid)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 14:52:35