在Linq语句中使用字典作为Regex.Replace模式的源

时间:2017-01-25 22:14:10

标签: c# regex linq

在C#中,我知道如何使用Regex.Replace Linq查询来替换输入字符串中的子字符串,如此代码示例所示。

var standards = _db.MapsFromOws.AsEnumerable().Select(m => 
                 m.Section).Distinct().AsEnumerable();
var enumerable = standards as IList<string> ?? standards.ToList();

const string elaPattern1 = @"LA.\d{1,2}-\d{1,2}.(\d{1,2}).([A-z]{1,2}).(\d{1,2})";
const string elaReplace1 = "$1.$2.$3";

var ela1 = enumerable
    .AsEnumerable()
    .Select(
        m =>
            new TranslationSelectModel
            {
                Section = m,
                /* If m is a match to elaPattern1 then replace else m*/
                Translation = Regex.Replace(m, elaPattern1, elaReplace1)
            })
    .OrderBy(m => m.Section).AsEnumerable();

如果我只需要替换一个模式,那么这很有效,但如果我必须在同一个列表中应用一组模式替换呢?

我知道使用Dictionary<string,string>作为正则表达式模式和替换字符串的来源。例如,

var regexPatternDictionary = new Dictionary<string, string>()
{
  {@"LA.\d{1,2}-\d{1,2}.(\d{1,2}).([A-z]{1,2}).(\d{1,2})","$1.$2.$3"},
  {@"MA.9-12.HS.([A-z])-([A-z]{0,3}).([A-z]).(\d)(.[A-z])*","HS.$1-$2.$3.$4$5"}
};

我的问题是如何使用Regex.Replace()以便它将枚举中的每个项目与正则表达式字典匹配而不是单个字符串变量?

我在脑海中看到的算法是:

  • 对于可枚举中的每个项目
    • 如果item与字典匹配,则应用替换
  • 循环到下一个项目

1 个答案:

答案 0 :(得分:2)

不确定我是否100%理解您的问题,但尝试这样的事情:

var result = enumerable.Select(x => replaceDictionary
                                   .Aggregate(x, (y,z) => Regex.Replace(y, z.Key, z.Value))
                       .ToArray()