Given a file with this format
// Colour
$primary-colour: if(@Model.PrimaryColour, @primaryColour, #afd05c);
$secondary-colour: if(@secondaryColour, @secondaryColour, #323f47);
// and so on
I'm trying to replace the @Model.Whatever based on a dictionary with would be something like this
var dictionary = new Dictionary<string, string>
{
{"primaryColour", "blue"},
{"secondaryColour", "red"}
};
But I'm struggling to find a way to so.
I was thinking of doing something like this:
private static String Replace(String str)
{
var dictionary = new Dictionary<string, string>
{
{"primaryColour", "blue"},
{"secondaryColour", "red"}
};
string variableValue;
string pattern = @"@Model.(?<name>\w)";
dictionary.TryGetValue(FirstCharacterToLower("${name}"), out variableValue);
var replacePattern = String.Format("{0}", variableValue);
return Regex.Replace(str, pattern, replacePattern, RegexOptions.IgnoreCase);
}
private static string FirstCharacterToLower(string str)
{
Console.WriteLine(str);
if (String.IsNullOrEmpty(str) || Char.IsLower(str, 0))
return str;
return Char.ToLowerInvariant(str[0]) + str.Substring(1);
}
But what I'm passing to the FirstCharacterToLower is just a string {name} and I'm stuck there. Can't think of a way to do it.
Any idea where to go from here?
Thanks
Edit: Based on sln comment I made this and it works
using System;
using System.Text.RegularExpressions;
using System.Collections.Generic;
public class Program
{
public static void Main()
{
var input = @"
// Colour
$primary-colour: if(@Model.PrimaryColour, @Model.PrimaryColour, #afd05c);
$secondary-colour: if(@Model.SecondaryColour, @Model.SecondaryColour, #323f47);";
Console.WriteLine(Replace(input));
}
private static String Replace(String str)
{
var dictionary = new Dictionary<string, string>
{
{"primaryColour", "blue"},
{"secondaryColour", "red"}
};
var regex = new Regex(@"@Model\.(?<name>\w+)");
var output = regex.Replace(str, v =>
{
string outVariable;
dictionary.TryGetValue(GetNameOfVariable(v.Groups["name"].Value), out outVariable);
return outVariable;
});
return output;
}
private static string GetNameOfVariable(string str)
{
Console.WriteLine(str);
if (String.IsNullOrEmpty(str) || Char.IsLower(str, 0))
return str;
return Char.ToLowerInvariant(str[0]) + str.Substring(1);
}
}
string pattern = @"@Model\.(?<name>\w+)";