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

如何通过正则表达式获取字符串中各匹配子模式的对应内容?

实现正则子模式与匹配内容的映射(C#)

核心问题与修正

首先要解决两个基础问题:

  1. 正则转义错误:原代码中的"\d{1,}D\d{1,}"会被C#编译器解析为无效转义字符,必须改为@"\d{1,}D\d{1,}"(逐字字符串)或"\\d{1,}D\\d{1,}"(双反斜杠转义)。
  2. 缺少捕获组:原正则没有分组标记,无法单独提取每个子模式的匹配内容,需要给每个要提取的子部分添加()捕获组,修正后的正则为@"(\d{1,})(D)(\d{1,})"。

实现代码

由于需求中存在重复的键(两个\d{1,}),而Dictionary<string, string>不允许重复键,这里提供两种实现方案:

方案1:用List存储(符合需求格式)

string pattern = @"(\d{1,})(D)(\d{1,})";
string str = "2D3";
var regex = new Regex(pattern);
Match matchResult = regex.Match(str);

if (matchResult.Success)
{
    // 定义每个捕获组对应的子模式
    string[] subPatterns = { @"\d{1,}", "D", @"\d{1,}" };
    List<KeyValuePair<string, string>> matchPairs = new List<KeyValuePair<string, string>>();

    // 遍历捕获组(索引从1开始,0为整个匹配结果)
    for (int i = 1; i < matchResult.Groups.Count; i++)
    {
        matchPairs.Add(new KeyValuePair<string, string>(
            subPatterns[i - 1],
            matchResult.Groups[i].Value
        ));
    }

    // 输出结果(模拟Log逻辑)
    foreach (var pair in matchPairs)
    {
        Console.WriteLine($"{{\"{pair.Key}\", \"{pair.Value}\"}}");
    }
}

方案2:用Dictionary存储(处理重复键)

如果必须使用Dictionary,可以给重复键添加序号后缀避免冲突:

string pattern = @"(\d{1,})(D)(\d{1,})";
string str = "2D3";
var regex = new Regex(pattern);
Match matchResult = regex.Match(str);

if (matchResult.Success)
{
    string[] subPatterns = { @"\d{1,}", "D", @"\d{1,}" };
    Dictionary<string, string> matchDict = new Dictionary<string, string>();

    for (int i = 1; i < matchResult.Groups.Count; i++)
    {
        // 给重复键添加序号
        string key = $"{subPatterns[i - 1]}_{i}";
        matchDict.Add(key, matchResult.Groups[i].Value);
    }

    // 输出结果
    foreach (var kvp in matchDict)
    {
        Console.WriteLine($"{{\"{kvp.Key}\", \"{kvp.Value}\"}}");
    }
}

关键说明

  • 捕获组通过()定义,Match.Groups会按顺序保存每个组的匹配内容,索引1对应第一个捕获组,以此类推。
  • 若需求严格要求重复键,List<KeyValuePair<string, string>>是更合适的选择,因为Dictionary的键必须唯一。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.15 20:13:24