0

I have a string like this:

string source = hello{1}from{2}my{3}world

And an array like this:

var valArray = new[] { "Val0", "Val1", "Val2", "Val3" };

I want to replace "{index}" substring with appropriate values from array.

I've already written the code, but it looks ugly

var valArray = new[] { "Val0", "Val1", "Val2", "Val3" };
var source = "hello{1}from{2}my{3}world";
var substr = source;
string pattern = $"{Regex.Escape(start)}{".+?"}{Regex.Escape(end)}";

foreach (Match m in Regex.Matches(source, pattern))
{
    var value = m.Groups[0].Value;
    var ind = Convert.ToInt32(m.Groups[0].Value.TrimStart(start.ToCharArray()).TrimEnd(end.ToCharArray()));
    substr = substr.Replace(value, valArray[ind]);
}
return substr;

Any tips how to get this solved?

Thanks!

Red
  • 2,728
  • 1
  • 20
  • 22

3 Answers3

3

I think you're looking for String.Format:

string result = string.Format(source, valArray); // "helloVal1fromVal2myVal3world"

Just keep in mind that it's indexing from 0, not from 1.

Gediminas Masaitis
  • 3,172
  • 14
  • 35
0

Use Regex.Replace(string input, string pattern, MatchEvaluator evaluator)

var valArray = new[] { "Val0", "Val1", "Val2", "Val3" };
var source = "hello{1}from{2}my{3}world";

string result = Regex.Replace(
    source,
    "{(?<index>\\d+)}",
    match => valArray[int.Parse(match.Groups["index"].Value)]);
Kalten
  • 4,092
  • 23
  • 32
0
[Test]
public void SO_36103066()
{
    string[] valArray = new[] { "Val0", "Val1", "Val2", "Val3" };
    //prefix array with another value so works from index {1}
    string[] parameters = new string[1] { null }.Concat(valArray).ToArray(); 
    string result = string.Format("hello{1}from{2}my{3}world", parameters);
    Assert.AreEqual("helloVal0fromVal1myVal2world", result);
}
weston
  • 54,145
  • 21
  • 145
  • 203