给定一个具有这种格式的文件
// Colour
$primary-colour: if(@Model.PrimaryColour, @primaryColour, #afd05c);
$secondary-colour: if(@secondaryColour, @secondaryColour, #323f47);
// and so on
我正在尝试替换 @Model.Whatever 基于字典的内容会是这样的
var dictionary = new Dictionary<string, string>
{
{"primaryColour", "blue"},
{"secondaryColour", "red"}
};
但我正在努力寻找一种方法。
我正在考虑做这样的事情:
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);
}
但是我传递给 FirstCharacterToLower 的只是一个字符串 {name} 并且我被困在那里。想不出办法。
知道接下来该去哪里吗?
谢谢
编辑:根据 sln 评论,我做了这个并且它有效
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);
}
}
最佳答案
正如 @sln 所说,你必须使用委托(delegate)。
private static String Replace(String str)
{
var dictionary = new Dictionary<string, string>
{
{"primaryColour", "blue"},
{"secondaryColour", "red"}
};
string pattern = @"@Model\.(?<name>\w+)";
return Regex.Replace(str, pattern, m =>
{
string key = m.Groups["name"].Value;
key = FirstCharacterToLower(key);
string value = null;
if (dictionary.TryGetValue(key, out value))
return value;
else
return m.Value;
});
}
关于c# - 替换为字符串中给定模式的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32077067/