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

编写正则表达式提取计算式中特定正负整数与浮点数

Hey there! Let's solve this regex problem where we need to extract numbers from a calculation string, but only keep the negative sign if it comes right after * or /. Here's how to do it step by step:

The Core Requirement Breakdown

We need to:

  • Extract positive numbers when they follow + or - (since those are addition/subtraction operators)
  • Keep the negative sign only when the number follows * or /
  • Support both integers and floating-point numbers
  • Ensure cross-browser compatibility (no fancy regex features that don't work in older browsers)
  • Differentiate from generic positive/negative float regexes (which capture all signs regardless of context)

The Solution Regex

Here's the regex that fits all these needs:

/(?:[*\/]-)?\d+(?:\.\d+)?/g

Regex Breakdown

Let's break down each part to understand how it works:

  • (?:[*\/]-)?: A non-capturing group that matches either *- or /- (the only places we want to keep the negative sign). The ? makes this group optional, so it won't interfere with positive numbers.
  • \d+: Matches one or more digits (the integer part of our number).
  • (?:\.\d+)?: Another non-capturing group for floating-point numbers—this matches a decimal point followed by one or more digits, and it's optional to support integers.
  • /g: The global flag ensures we find all matches in the string, not just the first one.

Test Code

Let's put this into action with your example string:

var str = "2-1+7*-777/-0.001+0.99";
var array = str.match(/(?:[*\/]-)?\d+(?:\.\d+)?/g);
console.log(array); // Output: ["2", "1", "7", "-777", "-0.001", "0.99"]

Why This Is Different From Generic Regexes

A generic positive/negative float regex like /[-+]?\d+(?:\.\d+)?/g would capture -1 from 2-1 as a negative number, which is not what we want. Our regex specifically ignores negative signs that follow + or - (since those are operators), only preserving the sign when it's tied to a multiplication/division operation.

Edge Case Handling

  • If your calculation strings might start with a negative number (e.g., -2+3*-4) and you want to keep that leading negative sign, you can adjust the regex to include an optional leading negative sign:
    /(?:^-|[*\/]-)?\d+(?:\.\d+)?/g
    
    This would extract ["-2", "3", "-4"] from -2+3*-4.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 03:31:42