我有一个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'的一部分。比赛应该是*动态*。 –