假设我有一本字典(单词及其替换):
var replacements = new Dictionary<string,string>();
replacements.Add("str", "string0");
replacements.Add("str1", "string1");
replacements.Add("str2", "string2");
...
输入字符串为:
string input = @"@str is a #str is a [str1] is a &str1 @str2 one test $str2 also [str]";
编辑:
预期输出:
string0 is a string0 is string0 is string1 string2 one test string2
我想用字典中相应的条目/值替换所有出现的“ [CharSymbol]word ” 。
其中Charsymbol可以是 @#$%^&*[] .. 也可以是单词有效后的 ']' ,即 [str] 。
我尝试了以下替换
string input = @"@str is a #str is a [str1] is a &str1 @str2 one test $str2 also [str]";
string pattern = @"(([@$&#\[]+)([a-zA-Z])*(\])*)"; // correct?
Regex re = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
// string outputString = re.Replace(input,"string0");
string newString = re.Replace(input, match =>
{
Debug.WriteLine(match.ToString()); // match is [str] #str
string lookup = "~"; // default value
replacements.TryGetValue(match.Value,out lookup);
return lookup;
});
我如何获得匹配为 str 、 str1 等,即没有字符符号的单词。