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

如何拆分字符串并替换字典集合内匹配项为对应列表键?

解决字符串匹配替换并拆分的方案

嘿,我来帮你搞定这个需求!我们的目标是把原句子拆分成列表,把字典里存在的字符串替换成对应键,同时保留其他部分。下面是具体的实现思路和代码:

核心思路

  1. 先建立字符串到键的反向映射,这样匹配到子串后能快速找到对应的键;
  2. 用正则表达式找出原句子中所有匹配字典值的子串;
  3. 遍历这些匹配结果,把原字符串切割成「非匹配文本」+「替换后的键」的片段,依次加入结果列表;
  4. 最后处理字符串末尾剩下的未匹配部分。

完整代码示例

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        // 原句子
        string originalSentence = "You ask your questions on StackOverFlow.com";
        
        // 给定的字典集合
        Dictionary<int, List<string>> collections = new Dictionary<int, List<string>>() 
        { 
            { 1, new List<string>() { "You", "your" } }, 
            { 2, new List<string>() { "Stack", "Flow" } }, 
        };

        // 1. 构建字符串到键的反向映射,方便快速查找
        var termToKey = collections
            .SelectMany(kv => kv.Value.Select(s => new { Term = s, Key = kv.Key }))
            .ToDictionary(item => item.Term, item => item.Key);

        // 2. 构建正则匹配模式:转义特殊字符,按字符串长度降序排序避免短匹配优先
        var allTerms = termToKey.Keys.Distinct().OrderByDescending(s => s.Length);
        string regexPattern = string.Join("|", allTerms.Select(Regex.Escape));
        Regex regex = new Regex(regexPattern);

        // 3. 切割字符串并替换匹配项
        List<string> resultList = new List<string>();
        int lastProcessedIndex = 0;

        foreach (Match match in regex.Matches(originalSentence))
        {
            // 添加匹配项之前的未匹配文本
            if (match.Index > lastProcessedIndex)
            {
                resultList.Add(originalSentence.Substring(lastProcessedIndex, match.Index - lastProcessedIndex));
            }
            // 添加替换后的键(转为字符串)
            resultList.Add(termToKey[match.Value].ToString());
            // 更新最后处理的位置
            lastProcessedIndex = match.Index + match.Length;
        }

        // 4. 添加最后剩下的未匹配文本
        if (lastProcessedIndex < originalSentence.Length)
        {
            resultList.Add(originalSentence.Substring(lastProcessedIndex));
        }

        // 输出结果
        Console.WriteLine(string.Join(", ", resultList));
        // 输出:1,  ask , 1,  questions on , 2, Over, 2, .com
    }
}

关键细节说明

  • 按长度降序排序:如果字典里有类似"Stack"和"StackOver"这样的重叠子串,长字符串会优先被匹配,避免出现错误的短匹配;
  • 正则转义:用Regex.Escape处理特殊字符(比如如果子串包含.或*),确保正则匹配准确;
  • 遍历匹配项:通过Match.Index和Match.Length精准切割原字符串,保证所有片段都被正确拆分和替换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 04:16:54