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

如何从以字母S开头的字符串中提取最多8位数字至int变量

提取字符串中以"S"开头的数字部分并转为int变量

核心思路

使用正则表达式匹配模式S(\d{1,8}),其中:

  • S:匹配固定开头字母
  • (\d{1,8}):捕获1到8位的数字(括号用于单独提取目标数字部分)
    找到匹配后,将捕获的数字字符串转换为int类型即可。

Python实现

import re

input_str = "blah blah blah blah S124 blah"
# 匹配S开头后接1-8位数字的模式,捕获数字部分
match_result = re.search(r'S(\d{1,8})', input_str)

if match_result:
    # 提取捕获组的数字字符串,转为int
    target_num = int(match_result.group(1))
    print(target_num)  # 输出:124,类型为int
else:
    print("未找到符合格式的内容")

如果需要提取所有符合条件的数字,可改用re.findall遍历处理:

all_matches = re.findall(r'S(\d{1,8})', input_str)
for num_str in all_matches:
    num = int(num_str)
    print(num)

Java实现

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class ExtractNumber {
    public static void main(String[] args) {
        String inputStr = "blah blah blah blah S124 blah";
        // 定义正则模式,注意Java中反斜杠需要转义
        Pattern pattern = Pattern.compile("S(\\d{1,8})");
        Matcher matcher = pattern.matcher(inputStr);

        if (matcher.find()) {
            // 提取捕获组内容并转为int
            int targetNum = Integer.parseInt(matcher.group(1));
            System.out.println(targetNum);  // 输出:124
        } else {
            System.out.println("未找到符合格式的内容");
        }
    }
}

提取所有匹配项可通过循环实现:

while (matcher.find()) {
    int num = Integer.parseInt(matcher.group(1));
    System.out.println(num);
}

C实现(C11及以上)

#include <iostream>
#include <regex>
#include <string>

int main() {
    std::string inputStr = "blah blah blah blah S124 blah";
    // 使用原始字符串字面量避免转义,匹配目标模式
    std::regex pattern(R"(S(\d{1,8}))");
    std::smatch matchResult;

    if (std::regex_search(inputStr, matchResult, pattern)) {
        // 提取捕获组的字符串并转为int
        int targetNum = std::stoi(matchResult[1].str());
        std::cout << targetNum << std::endl;  // 输出:124
    } else {
        std::cout << "未找到符合格式的内容" << std::endl;
    }
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 09:15:38