根据模式配置文本输出

Configure text output based on pattern

我正在开发一个基于用户创建的配置文件读取和写入文件的应用程序。作为其中的一部分,我想输出用户模式提供的阅读文本,但我想不出最好的方法。

示例:

配置中的输出模式:

{Name} version: {1}
{Name}_{1}

同时: 名称 - 将需要替换为字符串变量值

1,2,3... - 需要替换为相应的正则表达式匹配组值。

Regex.Replace 对我来说真的不起作用。它与 {Name} 等属性配合得很好,但我无法将数字转换为正则表达式匹配组。

我的第二个想法是将模式与 {} 值匹配并使用 switch case 替换它们,但这看起来不是最好的主意:

Regex a = new Regex("{(.*)}");

foreach (Match m in a.Matches(Pattern))
{
    switch (m.Groups[1].Value)
    {
        case "1":
            {                            
                return MatchedGroups[1].Value;
            }
        case "2":
            {                            
                return MatchedGroups[2].Value;
            }
        case "Name":
            {
                return Name;
            }
    }
}

编辑 1:

举例说明,我有什么,我想得到什么:

我有:

String InputText = "12/03/2015 *** [RandomText] // 1.04.1112V";
String regex = @"([0-9/]*) \*\*\* \[([A-Za-z]*)\] \/\/ (.*)";
  // #group 1 = 12/03/2015
  // #group 2 = RandomText
  // #group 3 = 1.04.1112V
String Name = "GoogleChrome";
String OutputPattern1 = "{1} - {Name} version {3}";
String OutputPattern2 = "{Name}_{3}";

并且有上面的变量和模式我想输出:

#1 : 12/03/2015 - GoogleChrome version 1.04.1112V

#2 : GoogleChrome_1.04.1112V

输出模式将由用户创建,因此我无法预测它们。

您可以使用

string InputText = "12/03/2015 *** [RandomText] // 1.04.1112V";
string regex = @"([0-9/]*) \*\*\* \[([A-Za-z]*)\] \/\/ (.*)";
string Name = "GoogleChrome";
string OutputPattern1 = "{1} - {Name} version {3}";
string OutputPattern2 = "{Name}_{3}";
string rx =  @"{(?:(\d+)|Name)}";
var match  = Regex.Match(InputText, regex);
if (match.Success) {
    Console.WriteLine(
        Regex.Replace(OutputPattern1, rx, x=>
            x.Groups[1].Success? match.Groups[int.Parse(x.Groups[1].Value)].Value : Name)
    );
    Console.WriteLine(
        Regex.Replace(OutputPattern2, rx, x=>
            x.Groups[1].Success? match.Groups[int.Parse(x.Groups[1].Value)].Value : Name)
    );
}
// => 12/03/2015 - GoogleChrome version 1.04.1112V
//    GoogleChrome_1.04.1112V

参见C# demo

{(?:(\d+)|Name)} 正则表达式匹配

  • { - 一个 { 字符
  • (?:(\d+)|Name) - 一个或多个数字(捕获到第 1 组)或 Name
  • } - 一个 } 字符。

如果第 1 组匹配,则使用整体匹配中的相应组替换 OutputPatternX 中的 {x} 子字符串,否则,使用 Name 变量文本。

如果您需要在替换之前检查组 ID 是否存在*(例如,您有 {4} 而您的正则表达式只有 3 个组),您将需要

Regex.Replace(OutputPattern1, rx, x=>
    !x.Groups[1].Success ? Name:
        int.Parse(x.Groups[1].Value) < match.Groups.Count ? 
            match.Groups[int.Parse(x.Groups[1].Value)].Value :
            x.Value)

参见 this C# demo