用变量替换存储在文本文件中的字符串中的占位符

Replace placeholders in string stored in a text file with variables

我有一个使用 C# 和 .NetCore 的 Windows UWP 应用程序。我有一种特殊类型的打印机,需要我发送特定的字符串来打印标签。因此,我将标签 definition/format 存储在一个单独的文本文件中。当应用程序加载并尝试打印时,我随后读取文本文件并加载字符串。但是,当我读取它时,这个字符串中有一些变量,我需要用实际数据替换它。目前,我使用占位符并用花括号突出显示它们。但是,如果更容易的话,我可以使用 parens 或其他东西。另外,我知道使用 string.Format,您通常会枚举要用数字替换花括号中的变量,但我选择使用文字来使定义文本文件更具可读性。

所以,这是我从文本文件中抓取并解析后的原始字符串(并将其存储在我的 class 属性 中)。

^XA ^LL300 ^FO125,575 ^A0R,30,30 ^FDRecipient: {Recipient} ^FS ^FO175,575 ^A0R,30,30 ^FDM/S: {EmpMail} ^FS ^FO275,575 ^A0R,30,30 ^FDTelephone: {EmpPhone} ^FS ^FO350,575 ^A0R,30,30 ^FDProcessed: {DateTime.Now} ^FS ^FO290,210 ^B7R,8,5,7,21,N ^FD{EmpNum} ^FS ^XZ

在这里,您可以看到花括号中的五个左右的变量占位符,我想将其替换为真实数据。

问题是,如何获取现在存储在 class 中的 属性 中的字符串,并用数据替换所有占位符。

为了提供一些背景信息,这是我目前所了解的。我对此没有任何例外,但它实际上并没有像它应该的那样替换数据。例如,下面的代码示例应该将 {DateTime.Now} 替换为实际的 DateTime.Now 但它没有,我仍然看到我的占位符。

  1. 这里是这个代码需要的两个字段

    public const string LabelDateTime = "{DateTime.Now}"; 私有字符串 locationLabel = string.Empty;

locationLabel 是在 class 的构造函数中填充的,当我在文本文件中读取上面显示的字符串时。

  1. 这是我将对所有占位符进行实际检测和替换的方法。现在,作为测试,我只做 DateTime.Now.

    private string replacePrintStringVariablesWithValues()
    {
        var finalPrintString = this.labelString;
        //Below we will check for and replace all of the possible variables to the print string.
        //TODO: we will need to refine/add more to this as labels are created. I tried to capture most now.
        if (labelString.Contains(LabelDateTime))
        {
            finalPrintString = ReplaceWholeWord(finalPrintString, LabelDateTime, DateTime.Now.ToString());
        }
    
        return finalPrintString;
    }
    
  2. 这里有一个使用正则表达式查找和替换的方法

    /// <summary>
    /// Uses regex '\b' as suggested in //
    /// </summary>
    /// <param name="original"></param>
    /// <param name="wordToFind"></param>
    /// <param name="replacement"></param>
    /// <param name="regexOptions"></param>
    /// <returns></returns>
    private static string ReplaceWholeWord(string completeString, string variableToReplace,
        string replacement, RegexOptions regexOptions = RegexOptions.IgnoreCase)
    {
        var pattern = string.Format(@"\b{0}\b", variableToReplace);
        var ret = Regex.Replace(completeString, pattern, replacement, regexOptions);
        return ret;
    }
    

但再次总结一下,如果我查看它 returns 之前的字符串 ret,我的 {DateTime.Now} 仍然只是这样说,并没有被实际的 DateTime.Now.另外,我确实检查了模式和替换参数,它们是正确的。

模式显示为

\b{DateTime.Now}\b

替换显示为

4/4/2017 5:40PM

元字符 \b 匹配单词 class 字符和非单词 class 字符之间的零宽度边界。

{} 不是 word-class 字符。所以你的模式不起作用。

删除 \b 或将其替换为 \s