假设如果我有一个字典(字及其替换)为:正则表达式替换取决于匹配单独更换
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]字'的所有出现。
其中Charsymbol可以@#$%^ & * [] ..也是 ']' 后半句是有效的,即[海峡。
我尝试以下方法为更换
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;
});
我如何拿到赛作为海峡,STR1等即没有charsymbol字。
nope..now it gives“string0 is a string0 is a str1] is a str2 str1 can be done string0是str2“ – Amitd 2012-08-02 16:07:14
我错过了[a-zA-Z]不匹配数字的事实。我已经更新了答案。 – 2012-08-02 16:20:24
thx很多..不错的作品漂亮:) – Amitd 2012-08-02 17:57:04