How to replace dynamic chunk {{chunk}} of a string in C#?

Asked

Viewed 413 times

6

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

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

List<Parametro> parametros = new List<Parametro>(){
   
  new Parametro(){
     
     Nome="parametro1",
     Valor="Programando em C#"
  },
new Parametro(){
     
     Nome="parametro2",
     Valor="preciso de ajuda!"
  }
}

How can I replace each section of string I receive at the value of each parameter?

  • 1

    I don’t quite understand what you want and what your problem is. You could be more specific?

  • I want to replace the values that are between keys with the value that is in the parameter class value property .

  • however I am not aware of how many keys will be in the text and the values I will need to replace. The text and values are dynamic

3 answers

5


If you can make it simple basically it’s using the method Replace() existing 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);
}

Behold working in the ideone. And in the .NET Fiddle. Also put on the Github for future reference. There I made an extension method also to use as a facilitator if this is used several times.

  • Thank you very much for the answer, very simple, tando code in the head nor realized it would be simple. I thank you.

4

You can use String Replace

Try:

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

teste = teste.Replace("{{parametro1}}", "valor1");
teste = teste.Replace("{{parametro2}}", "valor2");
  • Thank you very much for your reply.

4

first step, turn your parameter list into a dictionary, then assemble a regular expression to find all parameters in your input string, then replace.

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

  • Well complete your reply, thank you very much, I enjoyed it very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.