2012-08-02 65 views
1

假设如果我有一个字典(及其替换)为:正则表达式替换取决于匹配单独更换

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字。

回答

1

您正则表达式改成这样:

// Move the * inside the brackets around [a-zA-Z] 
// Change [a-zA-Z] to \w, to include digits. 
string pattern = @"(([@$&#\[]+)(\w*)(\])*)"; 

改变这一行:

replacements.TryGetValue(match.Value,out lookup); 

这样:

replacements.TryGetValue(match.Groups[3].Value,out lookup); 

注意:您IgnoreCase不必要的,因为你匹配博正则表达式中的大写和小写。

+0

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

+1

我错过了[a-zA-Z]不匹配数字的事实。我已经更新了答案。 – 2012-08-02 16:20:24

+0

thx很多..不错的作品漂亮:) – Amitd 2012-08-02 17:57:04

1

这套衣服?

(?<=[#@&$])(\w+)|[[\w+]] 

它匹配在您的示例如下:

@str是#str是[str]是& str1 @str2一个测试$ str2

+0

在大多数情况下工作,但不适用于[str1] ..匹配1]太 – Amitd 2012-08-02 15:24:42

+0

没有抱歉没有按预期工作..我更新了问题,以显示我是如何做匹配/替换。 – Amitd 2012-08-02 15:38:12

1

试试这个Regex([@$&#\[])[a-zA-Z]*(\])?,并用string0

替换你的代码应该像t他:

var replacements = new Dictionary<string, string> 
         { 
          {"str", "string0"}, 
          {"str1", "string1"}, 
          {"str2", "string2"} 
         }; 

String input="@str is a #str is a [str] is a &str @str can be done $str is @str"; 

foreach (var replacement in replacements) 
{ 
    string pattern = String.Format(@"([@$&#\[]){0}(\])?", replacement.Key); 
    var re = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled); 
    string output = re.Replace(input, 
           String.Format("{0}", replacement.Value)); 
} 
+0

添加输出字符串 – Amitd 2012-08-02 12:31:25

+0

更新了答案! – Ria 2012-08-02 14:22:10

+0

对于question.ie中的输入字符串,抱歉不起作用。 “@str is a #str is a [str1] is a&str1 @ str2 one test $ str2 also [str]” – Amitd 2012-08-02 15:34:21