如何编写正则表达式提取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 + integertwo 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:
-21-12--5+-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
相关产品推荐
相关产品推荐

