How to replace dynamic string {{snippet}} from a string in C #

5

I get a string which is dynamically generated example: "Dynamic text {{parametro1}}, plus a piece of text {{parametro2}}."

I have a code similar to this in C #: where the name is the same as in braces and the value property is the one that needs to be inserted instead.

List<Parametro> parametros = new List<Parametro>(){

  new Parametro(){

     Nome="parametro1",
     Valor="Programando em C#"
  },
new Parametro(){

     Nome="parametro2",
     Valor="preciso de ajuda!"
  }
}

The question is: how can I replace every stretch of string that I get, by the value of each parameter?

    
asked by anonymous 05.06.2016 / 23:23

3 answers

4

If you can basically basically do this, use the Replace() in .Net. If you need more sophistication, you would have to develop your own algorithm.

var texto = "Texto dinâmico {{parametro1}} , mais um pedaço do texto {{parametro2}}";
foreach (var item in parametros) {
    texto = texto.Replace("{{" + item.Nome.Trim() + "}}", item.Valor);
}

See running on dotNetFiddle and on CodingGround . There I made an extension method also to use as a facilitator if this is used multiple times.

    
05.06.2016 / 23:55
3

First step, transform your parameter list into a dictionary, then mount a regular expression to find all the parameters in your input string, then do the substitution.

public static string InterpolarString(string input, Parametro[] parametros)
{
    var dicParams = parametros.ToDictionary(param => param.Nome, param => param.Valor);     
    var regexp = new Regex(@"{{\w+}}");     
    var output = regexp.Replace(input, match => {
        var nome = match.Value.Substring(2, match.Value.Length - 4);
        return dicParams[nome];
    });
    return output;
}

Finally, an example working on DotNetFiddle

    
05.06.2016 / 23:53
3

You can use Replace from String

Try:

String teste = "Um teste {{parametro1}} outro teste {{parametro2}}";

teste = teste.Replace("{{parametro1}}", "valor1");
teste = teste.Replace("{{parametro2}}", "valor2");
    
05.06.2016 / 23:45