基于阵列的元素替换字符串 [英] Replace string based on array element

查看:124
本文介绍了基于阵列的元素替换字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些价值数组,也有一些参数string.I双双下面放置。
我想,以取代基于阵列元件的参数字符串。请帮我做THI。

 的String [] = arrayval {类型:1,行动:DOIT,消息:海};字符串参数=类型:类型] #Action:[动作] #Message:[信息] #OutMsg:[OutMsg]#@将RetVal:[将RetVal];我期望输出
字符串参数=类型:1#操作:DOIT#消息:海#OutMsg:[OutMsg]#@将RetVal:[将RetVal];


解决方案

不测试,应该增加一些检查,但看到@Ulugbek Umirov的版本:)

  VAR模式= @\\ [(。*?)\\];
VAR匹配= Regex.Matches(参数,图案);的foreach(在比赛中赛米){
    变种INB =[+ m.Groups [1] +];
    VAR的结果= arrayval.Select(S = GT; s.Split(':'))
                          .FindAll(β= GT; SS [0] == m.Groups [1])
                          。选择(SS => SS [1]);
    参数= Param.Replace(INB,结果[0]);
}

BTW ...有点短版@Ulugbek Umirov的应该只是正常工作:)

 参数= Regex.Replace(参数,@\\ [。?(+)\\],M =>
    arrayval.Select(S = GT; s.Split(新[] {':'},2))
            。凡(p值=> p.Length == 2)
            。凡(p值=指p [0] == m.Groups [1]。价值)
            。选择(p值=指p [1])
            .FirstOrDefault()? m.Value);

更新与更换0如果不存在:

 参数= Regex.Replace(参数,@\\ [。?(+)\\],M =>
    arrayval.Select(S = GT; s.Split(新[] {':'},2))
            。凡(p值=> p.Length == 2)
            。凡(p值=指p [0] == m.Groups [1]。价值)
            。选择(p值=指p [1])
            .FirstOrDefault()? 0);

I have a array with some value and also having some parameter string.I have placed both below. I would like to replace the parameter string based on array element. Please help me to do thi.

string[] arrayval = {"Type:1","Action:doit","Message:hai"};

string Param = "Type:[Type]#Action:[Action]#Message:[Message]#OutMsg:[OutMsg]#@RetVal:[RetVal]";

My Expected Output 


string Param = "Type:1#Action:doit#Message:hai#OutMsg:[OutMsg]#@RetVal:[RetVal]";

解决方案

not tested and some checks should be added but, see in version of @Ulugbek Umirov :)

var pattern = @"\[(.*?)\]";
var matches = Regex.Matches(Param, pattern);

foreach (Match m in matches) {
    var inb = "[" + m.Groups[1] + "]";
    var results = arrayval.Select (s  => s.Split(':'))
                          .FindAll(ss => ss[0] == m.Groups[1])
                          .Select (ss => ss[1]);
    Param = Param.Replace(inb, results[0]);
}

btw... a bit shorter version of @Ulugbek Umirov which should work just fine :)

Param = Regex.Replace(Param, @"\[(.+?)\]", m =>
    arrayval.Select(s => s.Split(new[] { ':' }, 2))
            .Where (p => p.Length == 2)
            .Where (p => p[0] == m.Groups[1].Value)
            .Select(p => p[1])
            .FirstOrDefault() ?? m.Value);

Update for replace with 0 if not exists:

Param = Regex.Replace(Param, @"\[(.+?)\]", m =>
    arrayval.Select(s => s.Split(new[] { ':' }, 2))
            .Where (p => p.Length == 2)
            .Where (p => p[0] == m.Groups[1].Value)
            .Select(p => p[1])
            .FirstOrDefault() ?? "0");

这篇关于基于阵列的元素替换字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆