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]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 等,即没有字符符号的单词。

4

3 回答 3

1

这适合吗?

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

它与您的示例中的以下内容匹配:

@ stris a # stris a [ str] is a & str1@ str2one test $str2

于 2012-08-02T12:04:38.837 回答
1

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

你的代码应该是这样的:

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)); 
} 
于 2012-08-02T12:04:40.337 回答
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不是必需的,因为您匹配正则表达式中的大小写。

于 2012-08-02T15:51:29.447 回答