2016-02-18 85 views
2

我有一个Dictionary<string, string>用于匹配一个新的string基于字典的字符串操作

Dictionary<string, string> dictionary = new Dictionary<string, string>() 
{ 
    { "foo", "bar" } 
}; 

我使用的方法来匹配string

public static string GetValueOrKeyAsDefault(this Dictionary<string, string> dictionary, string key) 
{ 
    string value; 
    return dictionary.TryGetValue(key, out value) ? value : key; 
} 

使用像这样:

string s1 = dictionary.GetValueOrKeyAsDefault("foo"); /* s1 equals "bar" */ 
string s2 = dictionary.GetValueOrKeyAsDefault("test"); /* s2 equals "test" */ 

我现在想部分匹配string,并保持这个字符串中的一部分匹配一个。

/* {0} is arbitrary, could be anything else */ 
Dictionary<string, string> dictionary = new Dictionary<string, string>() 
{ 
    { "SPROC:{0}", "{0}" }, 
    { "onClick='{0}(this)'", "{0}" } 
}; 

string s1 = dictionary.SomeMethod("SPROC:my_sproc"); /* s1 equals "my_sproc" */ 
string s2 = dictionary.SomeMethod("onClick='HandleOnClick(this)'"); /* s1 equals "HandleOnClick" */ 

我觉得regex可能是一种方式,但我不知道如何实现它。

+1

你的SomeMethod如何知道字符串的哪个部分匹配?你想达到什么结果? – CodeMonkey

+1

如果{0}'是任意的,这里的比赛规则是什么?如果值/键以键/值结尾?或者只有一个包含另一个?如果有几个符合要求? –

+0

@ user3387223我试图实现的结果是获得'string'的一部分。比赛应该是*动态*。 –

回答

2

请注意,在这里使用Dictionary<,>是“道德上”错误的...我会使用List<Tuple<Regex, string>>。这在道德上是错误的,原因有两个:各种键值的排序(所以优先级)不是“固定的”,并且可能是非常随机的,而且你不能利用Dictionary<,>的优势:O(1)完全匹配(TryGetValue)。

还有:

public static string SomeMethod(Dictionary<string, string> dictionary, string str) 
{ 
    foreach (var kv in dictionary) 
    { 
     var rx = new Regex(kv.Key); 

     if (rx.IsMatch(str)) 
     { 
      string replaced = rx.Replace(str, kv.Value); 
      return replaced; 
     } 
    } 

    return str; 
} 

Dictionary<string, string> dictionary = new Dictionary<string, string>() 
{ 
    { @"SPROC:(.*)", "$1" }, 
    { @"onClick='(.*)\(this\)'", "$1" }  
}; 

string replaced = SomeMethod(dictionary, "SPROC:my_sproc"); 

请注意,您必须使用Regex “语言”(见(.*)$1

没有无用Dictionary<,>

public static string SomeMethod(IEnumerable<Tuple<Regex, string>> tuples, string str) 
{ 
    foreach (var rr in tuples) 
    { 
     if (rr.Item1.IsMatch(str)) 
     { 
      string replaced = rr.Item1.Replace(str, rr.Item2); 
      return replaced; 
     } 
    } 

    return str; 
} 

var dictionary = new[] 
{ 
    Tuple.Create(new Regex("SPROC:(.*)"), "$1"), 
    Tuple.Create(new Regex(@"onClick='(.*)\(this\)'"), "$1"), 
}; 

string replaced = SomeMethod(dictionary, "SPROC:my_sproc"); 

作为旁注,我会在每个正则表达式的开头添加一个^和一个$在每个正则表达式的末尾,如"^SPROC:(.*)$",只是为了确保正则表达式不会匹配部分子字符串。

+0

谢谢你,你真的明白我想要做什么。你钉了它! –