我有一個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
可能是一種方式,但我不知道如何實現它。
你的SomeMethod如何知道字符串的哪個部分匹配?你想達到什麼結果? – CodeMonkey
如果{0}'是任意的,這裏的比賽規則是什麼?如果值/鍵以鍵/值結尾?或者只有一個包含另一個?如果有幾個符合要求? –
@ user3387223我試圖實現的結果是獲得'string'的一部分。比賽應該是*動態*。 –