C#用正则表达式高效替换变量

有的时候我们需要进行简单的字符串变量替换. 当然最新的.net已经支持 {name} 这种替换方式. 但是,老的.net是不支持的. 本方法是把“{{varName}}” 这种变量替换成 对应的数值.

例如

Week1 = 星期一
Week2 = 星期二
Week3 = 星期三
Week4 = 星期四
“今天是{{Week1}}, 明天是{{Week2}}

替换结果

“今天是星期一, 明天是星期二”

下面是代码

        /// <summary>
        /// 会自动替换 变量   把形如 "{{varName}}" 替换成对应的数值
        /// </summary>
        public static void ReplaceFileVar(string srcFile, string targetFile)
        { 
            /*
            * 设置webconfig连接字符串
            */
            string webconfigpath = Path.Combine("./", srcFile);
            //修改第一个数据库连接
            string webcofnigstring2 = File.ReadAllText(webconfigpath);

            webcofnigstring2 = ReplaceStringVar(webcofnigstring2);

            //循环替换所有的 {{DBSERVER}} 这种变量 效率比较低,改成上面的replace
            //foreach (Match item in mat)
            //{
            //    Console.WriteLine(item.Groups[1]);
            //    var name = item.Groups[1].Value;
            //    if (! string.IsNullOrEmpty( InstallContext.Get(name)))
            //    {
            //         webcofnigstring2.Replace(@"{{"+ name + "}}", InstallContext.Get(name));
            //    }
            //}

            File.WriteAllText(targetFile, webcofnigstring2);
        }


        /// <summary>
        /// 会自动替换 变量   把形如 "{{varName}}" 替换成对应的数值
        /// </summary>
        private static string ReplaceStringVar(string str)
        {
            Regex reg = new Regex(@"\{\{(.*?)\}\}");
            //var mat = reg.Matches(webcofnigstring2);

            str = reg.Replace(str,
                new MatchEvaluator(m =>
                     InstallContext.Get(m.Groups[1].Value) == string.Empty ? m.Value : InstallContext.Get(m.Groups[1].Value)
                ));
            return str;
        }

InstallContext.cs 顺便也贴一下

public static class InstallContext  
{
    private static Dictionary<string, string> kvs = new Dictionary<string,string> ();
    public static string Get(string index) 
    {
        if (kvs.ContainsKey(index)) 
        {
            return kvs[index];
        } else 
        {
            return string.Empty;
        }
    }
    public static void Set(string index, string value) 
    {
        kvs[index] = value;
    }
    //private static InstallContext instance = new InstallContext();
    //private InstallContext()
    //{
    //}
    //public static InstallContext GetInstance()
    //{ 
    //    return instance;
    //}
}

下面是使用方法

        private void button3_Click(object sender, EventArgs e)
        { 
            InstallContext.Set("WebSiteDBConnectstring",textBox1.Text);
            ReplaceFileVar("Web.config.tpl","Web.config"); 
        }

Web.config.tpl 文件内容

<?xml version="1.0"?>
<configuration>
{{WebSiteDBConnectstring}}
</configuration>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值