Search code examples
c#regexdictionarycase-insensitive

C# - Case Insensitive Regex.Replace function with dictionaries


I have a sentence like this My name is [name] and I'm [age] years old

I would like to replace the text inside of square brackets with something belonging to a dictionary. I googled a bit and I've found out about the Regex.Replace function so I've ended up with this code:

string sentence =  "My name is [name] and I'm [age] years old"
string someVariable1 = "John";
string someVariable2 = "34";

var replacements = new Dictionary<string, string>()
        {
            {"[name]", someVariable1},
            {"[age]", someVariable2},
        };

var replaced = Regex.Replace(sentence, string.Join("|", replacements.Keys.Select(k => Regex.Escape(k.ToString()))), m => replacements[m.Value]);

The problem is that the sentence is supposed to be an user input where I ask to type stuff inside square brackets in order to retrieve some variables. That's where my concernes start, is there a way to let the text inside square brackets to be case insensitive? I mean, is there a way that even if someone types "[NAME]" or "[Name]" instead of "[name]" it does the job? I've tried with regex syntax such as @"[[Nn]ame]" and with Regex.Options.IgnoreCase but I can't make it work. I suppose that's something I'm not understanding correctly.

Thank you.


Solution

  • Seems you just need to add a case-insensitive comparer to the dictionary. You also obviously need to apply RegexOptions.IgnoreCase in order for the Regex finder to search while ignoring case.

    var replacements = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
    {
        {"[name]", someVariable1},
        {"[age]", someVariable2},
    };
    

    dotnetfiddle