正则表达式将文本文件中的$(Key)替换为字典中的值



我想做这样的事情,我有一个包含键和值的字典,还有一个这样的文本文件:

Hello my name is $(Name) and my favorite movie is $(Movie).

我想在文件中读取并根据字典中的值替换$(…)的出现,所以在这种情况下,字典将有一个Name和Movie的键。

我该怎么做?如果我解析每个单词,匹配$(AnyWord)的正则表达式是什么,或者最好这样做:

foreach(var word in file)
{
    if (word.length > 3)
    {
        if (word.substring(0,2)=="$(" && word.substring(word.length-1)==")")
           Lookup word in dictionary 
    }
}

感谢

使用MatchEvaluator进行替换:

var replacements = new Dictionary<string,string>();
//populate the dictionary
string file = System.IO.File.ReadAllText("filepath");
file = Regex.Replace(file, @"$((?<key>[^)]+))", new MatchEvaluator(m => replacements.ContainsKey(m.Groups["key"].Value) ? replacements[m.Groups["key"].Value] : m.Value));

如果有任何语法错误,我深表歉意。我现在正在工作,没有C#编译器,所以回家后我必须修复它们。

如果你的文件不是很大,一个简单的解决方案就是反过来做。循环浏览字典中的所有项目并替换标记:

foreach(var item in dictionary) {
    var token = string.Format("$({0})", item.Key);
    file = file.Replace(token, item.Value);
}

您可以使用此正则表达式来查找类似$(word):的字符串

/($(w*))/i

解释:

/                      # regex delimiter
    (                  # matching brackets
        $             # the $
        (             # the (
            w*        # w = a to z
        )             # the )
    )                  # close matching brackets
/xi

修改器:i=不区分大小写,x=忽略regex中的空白(这样您就可以使其可读并进行这样的注释)

最新更新