簡體   English   中英

用數組中的值替換子字符串

[英]Replace substrings with values from array

我有一個像這樣的字符串:

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

像這樣的數組:

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

我想用數組中的適當值替換“ {index}”子字符串。

我已經寫了代碼,但是看起來很丑

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;

任何提示如何解決這個問題?

謝謝!

我認為您正在尋找String.Format

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

請記住,它是從0開始索引,而不是從1開始。

使用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)]);
[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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM