shtkuh
shtkuh

Reputation: 459

Variables replacing into string in C#

I have string in format

"sometext%1%-%2%blablabla%15%"

and collection of class Variable:

public class Variable
{
     public long Id { get; set; }
     public string Value { get; set; }
}

How can I replace all substrings like "%{ID Number}%" with Value field of Variable which Id equals to {ID Number} (for example replace "%1%" with Variable Value field whose ID = 1) using Regex.Replace method or something similar?

Upvotes: 3

Views: 2492

Answers (3)

oleksii
oleksii

Reputation: 35925

Something like this?

var data = new List<Variable>
{
    new Variable{Id = 1,Value = "value1"},
    new Variable{Id = 2, Value = "value2"}

};

var sb = new StringBuilder("sometext%1%-%2%blablabla%15%");

foreach (Variable t in data)
{
    string oldString = String.Format("%{0}%", t.Id);
    sb.Replace(oldString, t.Value);
}

//sometextvalue1-value2blablabla%15%
string output = sb.ToString();

Upvotes: 3

jdehaan
jdehaan

Reputation: 19938

You can use your own match evaluator. This is untested, but the solution should look similar to this code:

String processed = Regex.Replace (rawInput, @"%(\d+)%", MyMatchEvaluator);

private string MyMatchEvaluator (Match match)
{
    int id = int.Parse (match.Captures[0].Value);
    return _variables.Where(x => x.Id == id).Value;
}

Where _variables is your collection of variables and rawInput your input string.

Upvotes: 4

Rune Grimstad
Rune Grimstad

Reputation: 36330

There is nothing built in to .Net that does this, but there are several implementations of this kind of functionality.

Check out this blog post by Phil Haack where he explores several implementations. The blog post is from 2009, but the code should be quite usable still :-)

Upvotes: 0

Related Questions