C#正则表达式替换为文件内容

时间:2015-08-31 09:45:50

标签: c# regex

输入类似include("blablabal.bla"),我想用文件blablabal.bla中的内容替换它。是否有可能在C#?

由于

1 个答案:

答案 0 :(得分:2)

您应该查看Regex.Replace方法。有一个版本接收匹配代表,可以像这样使用:

var include = new Regex(@"include\(""(?<filename>.*?)""\)");
var input   = File.ReadAllText("c:\\sample.txt");
var output  = include.Replace(input, (match) =>
{
    if (match.Success)
    {
        var filename = match.Groups["filename"].Value;
        // TODO: make this secure. Imagine this: include("c:\passwords.txt")
        if (File.Exists(filename))
            return File.ReadAllText(filename);
    }
    return "Invalid directive: " + match.Value;
});