0

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

1 Answer 1

2

Not sure if I understand your problem 100%, but try something like this:

var result = enumerable.Select(x => replaceDictionary
                                   .Aggregate(x, (y,z) => Regex.Replace(y, z.Key, z.Value))
                       .ToArray()
Sign up to request clarification or add additional context in comments.

2 Comments

It's a good hint. The Debug output shows that produces a translation. I need to present the input as field 1 and the translation as field 2. Trying to work that out on my side.
Here's what did the job: var vm = enumerable .Select(x => new TranslationSelectModel {Section=x, Translation=regexPatternDictionary.Aggregate(x, (y, z) => Regex.Replace(y, z.Key, z.Value))}) .AsEnumerable();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.