只需发布我使用@Youssef13 建议的方法的最终代码
Dictionary<Tuple<string, string>,Tuple<string,string>> sourcecolumncodeandvalue = new Dictionary<Tuple<string, string>, Tuple<string, string>>();
sourcecolumncodeandvalue.Add(Tuple.Create("Source1", "Column1"), Tuple.Create("ABC", "Col1"));
sourcecolumncodeandvalue.Add(Tuple.Create("Source2", "Column2"), Tuple.Create("DEF", "Col2"));
Dictionary<string, string> codeandvaluereplacementlist = new Dictionary<string, string>();
var pattern = @"\[(.*?)\]\.\[(.*?)\]";
var filetext = "anytext[Source1].[anytext:Column1:anytext]anytext anytext[Source2].[anytext:Column2:anytext]anytext";
var matchesfound = System.Text.RegularExpressions.Regex.Matches(filetext, pattern); //find the pattern [].[]
foreach (System.Text.RegularExpressions.Match m in matchesfound)
{
string datasource = string.Empty;
string columnname = string.Empty;
string replacementtext = string.Empty;
string[] sourceandcolumnsplit = m.Value.ToString().Split('.');//split [].[] into two based on '.' character
datasource = sourceandcolumnsplit[0].Replace("[","").Replace("]",""); //remove square brackets
//Column value is in between ':' character (ex: anytext:Column2:anytext) so split it further
string[] columnsplit = sourceandcolumnsplit[1].Split(':');
columnname = columnsplit[1];
//We got the source and column codes, now get corresponding values from the dictionary
Tuple<string,string> sourceandcolumnvalues;
sourcecolumncodeandvalue.TryGetValue(Tuple.Create(datasource, columnname),out sourceandcolumnvalues);
//construct the replacement value string for each code string
codeandvaluereplacementlist.Add(m.Value.ToString(), "[" + sourceandcolumnvalues.Item1 + "]." + columnsplit[0] + ":" + sourceandcolumnvalues.Item2 + ":" + columnsplit[2]);
}
//Finally loop through all code matches and replace with values in the file text
foreach (var codeandvalue in codeandvaluereplacementlist)
{
filetext = filetext.Replace(codeandvalue.Key, codeandvalue.Value);
}