简体   繁体   English

变量在C#中替换为字符串

[英]Variables replacing into string in C#

I have string in format 我有格式的字符串

"sometext%1%-%2%blablabla%15%" “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? 如何使用Regex.Replace替换所有子字符串,例如"%{ID Number}%"其中Value字段为Id等于{ID Number} (例如,将"%1%"替换为ID = 1的"%1%"变量值”字段)方法或类似的东西?

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. 其中_variables是你的变量收集和rawInput您输入的字符串。

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

There is nothing built in to .Net that does this, but there are several implementations of this kind of functionality. .Net没有内置任何功能,但是这种功能有几种实现方式。

Check out this blog post by Phil Haack where he explores several implementations. 看看Phil Haack的这篇博客文章 ,他在那里探讨了几个实现。 The blog post is from 2009, but the code should be quite usable still :-) 博客文章是从2009年开始的,但代码应该还是可以使用的:-)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM