1
votes

Suppose if I have a dictionary (word and its replacements) as :

var replacements = new Dictionary<string,string>();
replacements.Add("str", "string0");
replacements.Add("str1", "string1");
replacements.Add("str2", "string2");
...

and an input string as :

 string input = @"@str is a #str is a [str1] is a &str1 @str2 one test $str2 also [str]";

Edit:
Expected output :

string0 is a string0 is string0 is string1 string2 one test string2

I want to replace all occurances of '[CharSymbol]word' with its corresponding entry/value from the dictionary.

where Charsymbol can be @#$%^&*[] .. and also ']' after the word is valid i.e. [str] .

I tried the following for replace

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;
         });

How do i get the match as str , str1 etc. i.e. word without charsymbol.

3

3 Answers

1
votes

Change your regex to this:

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

Change this line:

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

to this:

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

Note: Your IgnoreCase isn't necessary, since you match both upper and lower case in the regex.

1
votes

Does this suit?

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

It matches the following in your example:

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

1
votes

Try this Regex: ([@$&#\[])[a-zA-Z]*(\])?, and replace with string0

your code should be like this:

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)); 
}