我想阅读文字并替换被信号

时间:2017-08-25 14:15:00

标签: c# string

我有一大块文字,例如

string OriginalText = "Hello my name is <!name!> and I am <!age!> years old";

我正在努力编写一个我可以输入此文本的函数,它将返回相同的字符串,除了标记"<!""!>"包围的值将替换为实际值。我写了一些代码,但不知道如何进一步发展。

if(OriginalText.Contains("<!")) //Checks if Change is necessary
{
     string[] Total = OriginalText.Split( 
       new Char[] { '<', '!' }, 
       StringSplitOptions.RemoveEmptyEntries);

     if(Total[1].Contains("!>")) //Checks if closing tag exists
     {
         string ExtTag = Total[1].Split( 
           new Char[] { '<', '!' }, 
           StringSplitOptions.RemoveEmptyEntries)[0];

         ExtData.Add(Total[1].Split( 
           new Char[] { '<', '!' }, 
           StringSplitOptions.RemoveEmptyEntries)[0]);

         return Total[1];
     }
}

所需的输出是

"Hello my name is James and I am 21 years old"

我目前从数据库中获取此文本,因此此功能的目的是读取该文本并输入正确的信息。

编辑:弄清楚如何做到这一点我将在下面包含它但是我在一个名为mattersphere的程序中写这个,所以会引用非标准c#的函数,我会在旁边放置注释他们解释了他们的所作所为。

private string ConvertCodeToExtData(string OriginalText) //Accepts text with the identifying symbols as placeholders
    {
        string[] OriginalWords = OriginalText.Split(' '); //Creates array of individual words
        string ConvertedText = string.Empty;
        int Index = 0;

        foreach(string OriginalWord in OriginalWords) //Go through each word in the array
        {
            if(OriginalWord.Substring(0,1).Equals("<") && OriginalWord.Substring(OriginalWord.Length-1 ,1).Equals(">")) //Checks if Change is necessary
            {
                string[] ExtDataCodeAndSymbols = OriginalWord.Substring(1, OriginalWord.Length-2).Split('.');   //Decided to create 4 different parts inbetween the <> tags it goes Symbol(e.g £, $, #) . area to look . field . symbol  //separates the Code Identifier and the ExtData and Code
                try
                {
                    foreach(ExtendedData ex in this.CurrentSession.CurrentFile.ExtendedData) //Search through All data connected to the file, Extended data is essentially all the data from the database that is specific to the current user
                    {
                        if(ex.Code.ToLower() == ExtDataCodeAndSymbols[1].ToLower())
                        {
                            OriginalWords[Index] = ExtDataCodeAndSymbols[0] + ex.GetExtendedData(ExtDataCodeAndSymbols[2]).ToString() + ExtDataCodeAndSymbols[3]; //Replace code with new data
                            break;
                        }
                    }
                }
                catch (Exception ex)
                {
                    System.Windows.Forms.MessageBox.Show("Extended Data Field " + ExtDataCodeAndSymbols[1] + "." + ExtDataCodeAndSymbols[2] + " Not found, please speak to your system administrator"); //Handles Error if Ext Data is not found
                }
            }
            Index++;
        }

        foreach(string Word in OriginalWords)
        {
            ConvertedText += Word + " "; //Adds all words into a single string and adds space
        }

        ConvertedText.Remove(ConvertedText.Length -1, 1); //Removes Last Space

        return ConvertedText;
    }

文字显示“Hello我的名字是&lt; .Person.name。&gt;我在我的银行帐户中有&lt;£.Account.Balance。&gt;”并且出来了“你好我的名字是詹姆斯和我我的银行账户里有100英镑“

符号是可选的,但是“。”是必要的,因为它们用于在函数的早期分割字符串

3 个答案:

答案 0 :(得分:4)

如果您必须使用<!...!>占位符,我建议正则表达式

  using System.Text.RegularExpressions;

  ...

  string OriginalText = "Hello my name is <!name!> and I am <!age!> years old";

  Dictionary<string, string> substitutes = 
    new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase) {
      { "name", "John" },
      { "age", "108"},
    };

  string result = Regex
    .Replace(OriginalText, 
             @"<!([A-Za-z0-9]+)!>", // let placeholder contain letter and digits
             match => substitutes[match.Groups[1].Value]);

  Console.WriteLine(result);

结果:

  Hello my name is John and I am 108 years old 

答案 1 :(得分:2)

假设您坚持使用该格式,并假设您提前知道了字段列表,则可以编写替换字符串的字典,并将其替换。

        //Initialize fields dictionary
        var fields = new Dictionary<string, string>();
        fields.Add("name", "John");
        fields.Add("age", "18");

        //Replace each field if it is found
        string text = OriginalText;
        foreach (var key in fields.Keys)
        {
            string searchFor = "<!" + key + "!>";
            text = text.Replace(searchFor, fields[key]);
        }

如果替换字段的值来自域对象,则可以使用反射迭代属性:

class Person
{
    public string Name { get; set; }
    public int Age { get; set; }

}

class Program
{
    const string OriginalText = "Hello my name is <!name!> and I am <!age!> years old";
    public static void Main()
    {
        var p = new Person();
        p.Age = 18;
        p.Name = "John";

        //Initialize fields dictionary
        var fields = new Dictionary<string, string>();
        foreach (var prop in typeof(Person).GetProperties(BindingFlags.Public | BindingFlags.Instance))
        {
            fields.Add(prop.Name, prop.GetValue(p).ToString());
        }

        ///etc....

如果您需要将标记检查设置为不区分大小写,则可以使用此标记而不是String.Replace()

    string searchFor = @"\<\!" + key + @"\!\>";
    text = Regex.Replace(text, searchFor, fields[key], RegexOptions.IgnoreCase);

答案 2 :(得分:0)

我认为你正在寻找这个:

var str = string.Format("Hello my name is {0} and I am {1} years old", name, age);

或者,从C#6开始,你可以使用它:

var str = $"Hello my name is {name} and I am {age} years old";