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

如何编写Regex提取字符串"07887"中的指定数字分组?

Solution to Extract Specific Digit Groups with Regex

Alright, let's break down how to pull ['0','78','87'] from the string "07887" using regex. Your requirement is clear: grab the first single digit, then split the remaining four digits into two pairs. Here's a straightforward approach:

The Regex Pattern

We can use capturing groups to target each segment exactly. The pattern we'll use is:

^(\d)(\d{2})(\d{2})$

Let's break down what each part does:

  • ^ : Anchors the match to the start of the string, ensuring we don't skip any leading characters.
  • (\d) : First capturing group—matches a single digit (this gives us the '0').
  • (\d{2}) : Second capturing group—matches exactly two consecutive digits (this grabs '78').
  • (\d{2}) : Third capturing group—matches the final two consecutive digits (this gets '87').
  • $ : Anchors the match to the end of the string, ensuring we cover the entire 5-digit input with no extra characters left over.

Code Example (Python)

Here's how to implement this in Python to get your desired output list:

import re

input_str = "07887"
regex_pattern = r"^(\d)(\d{2})(\d{2})$"

match_result = re.match(regex_pattern, input_str)
if match_result:
    # Convert the tuple of captured groups to a list
    extracted_values = list(match_result.groups())
    print(extracted_values)  # Output: ['0', '78', '87']

Code Example (JavaScript)

If you're working in JavaScript, the approach is similar—just note that match() returns the full match plus groups, so we slice off the first element:

const inputStr = "07887";
const regexPattern = /^(\d)(\d{2})(\d{2})$/;

const matchResult = inputStr.match(regexPattern);
if (matchResult) {
    const extractedValues = matchResult.slice(1);
    console.log(extractedValues);  // Output: ['0', '78', '87']
}

Notes

  • This pattern only works for exactly 5-digit strings, which aligns perfectly with your input "07887".
  • If you need to handle cases where there might be non-digit characters (though your input doesn't mention this), you can replace \d with [0-9] for explicit digit matching.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.20 11:38:19