In C#, I know how to use Regex.Replace a Linq query to replace substrings within an input string, as shown in this code sample.
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();
This works well if there is only one pattern I need to replace, but what if I have to apply a set of pattern-replacements in the same list?
I had an idea of using a Dictionary<string,string> as a source of Regex patterns and replacement string. For example,
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"}
};
My question is how I would be able to use Regex.Replace() so that it matches each item in the enumerable to the regular expression dictionary instead of a single string variable?
The algorithm I'm seeing in my mind is:
- For each item in enumerable
- If item is a match to a dictionary, then apply replacement
- Loop to next item