3

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?

1
  • I would use first Regex.Match to get all occurences of a number (use [\d]+ or something like it). Then it depends on how you stored those instances of Variable. Commented Jan 5, 2012 at 13:44

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

1 Comment

2 little fixes: using Single instead of Where and we have remove all "%" symbols from match.Captures[0].Value
3

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();

Comments

0

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 :-)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.