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

如何编写正则表达式提取4个整数与3个操作符?

Hey there! Let's get your regex sorted so it captures exactly those 4 integers and 3 operators while ignoring the line number at the start.

The Problem Breakdown

You need to:

  • Skip the line number format at the start of the line (like [9] )
  • Capture 4 integers (including negative ones with their - sign)
  • Capture 3 operators (like -, -, + as in your example)

The Solution Regex

Here's a regex that does exactly what you need:

^\[\d+\]\s*(-?\d+)\s*([+-])\s*(-?\d+)\s*([+-])\s*(-?\d+)\s*([+-])\s*(-?\d+)

Let's Break It Down

Let's walk through each part to understand how it works:

  • ^\[\d+\]\s*: This matches and skips the line number at the start. ^\[ anchors to the beginning of the line and matches [, \d+ matches one or more digits, \] matches the closing ], and \s* skips any whitespace after the line number.
  • (-?\d+): This captures an integer. (-?) matches an optional negative sign, and \d+ matches one or more digits (the number itself).
  • \s*([+-])\s*: This captures an operator (+ or -). The \s* on either side handles any whitespace between the number and operator, so it works whether there's space or not.
  • We repeat the pattern of operator + integer two more times to get the total 3 operators and 4 integers.

Testing with Your Example

If your input line is something like [9] -21 - 12 - -5 + -26, this regex will capture these 7 groups in order:

  1. -21
  2. -
  3. 12
  4. -
  5. -5
  6. +
  7. -26

Perfect match for what you need! If you need to support more operators (like * or /), just update the [+-] part to [+\-*/] (make sure to escape the - or place it at the start/end of the character set to avoid issues).

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 10:25:04