2016-02-18 83 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

謝謝你,你真的明白我想要做什麼。你釘了它! –