繁体   English   中英

C#RegEx一个字典来替换字符串的出现

[英]C# RegEx a Dictionary to replace occurances of a string

我试图用C#中的Dictionary中的值替换属性名称的出现。

我有以下词典:

Dictionary<string, string> properties = new Dictionary<string, string>()
{
    { "property1", @"E:\" },
    { "property2", @"$(property1)\Temp"},
    { "property3", @"$(property2)\AnotherSubFolder"}
};

其中键是属性名称,值只是一个字符串值。 我基本上想要遍历值,直到所有设置属性都被替换。 语法类似于MSBuild属性名称。

这应该最终将属性3评估为E:\\ Temp \\ AnotherSubFolder。

如果功能的RegEx部分可以工作,这将是有帮助的,这是我坚持的地方。

我已经尝试了编辑我正则表达式的REFiddle 这里

以下正则表达式模式适用于此:

/\$\(([^)]+)\)/g

鉴于案文:

$(property2)\AnotherSubFolder

它突出显示$(property2)。

但是,将它放在.NET小提琴中,我没有得到以下代码的任何匹配:

var pattern = @"\$\(([^)]+)\)/g";
Console.WriteLine(Regex.Matches(@"$(property2)AnotherSubFolder", pattern).Count);

哪个输出0。

我不太清楚为什么在这里。 为什么我的比赛结果为零?

  1. .NET默认情况下应全局匹配。
  2. 我不知道的支持/g ,因为这是一个Perl主义,因此将其删除,以及领先的/ ,.NET试图逐字匹配。

正则表达式在这里可能有些过分,如果您的属性或值包含特殊字符,或者将被评估为正则表达式的字符,甚至可能会引入问题。

一个简单的替换应该工作:

Dictionary<string, string> properties = new Dictionary<string, string>()
{
    { "property1", @"E:\" },
    { "property2", @"$(property1)\Temp"},
    { "property3", @"$(property2)\AnotherSubFolder"}
};

Dictionary<string, string> newproperties = new Dictionary<string, string>();

// Iterate key value pairs in properties dictionary, evaluate values
foreach ( KeyValuePair<string,string> kvp in properties ) {
  string value = kvp.Value;
  // Execute replacements on value until no replacements are found
  // (Replacement of $(property2) will result in value containing $(property1), must be evaluated again)
  bool complete = false;
  while (!complete) {
    complete = true;
    // Look for each replacement token in dictionary value, execute replacement if found
    foreach ( string key in properties.Keys ) {
      string token = "$(" + key + ")";
      if ( value.Contains( token ) ) {
        value = value.Replace( "$(" + key + ")", properties[key] );
        complete = false;
      }
    }
  }
  newproperties[kvp.Key] = value;
}

properties = newproperties;

暂无
暂无

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

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