Regex Replace - Multiple Characters

I have 20 or so characters that I need to replace with various other characters in a block of text. Is there a way to do this in one regex, and what would this regex be? Or is there an easier way to do this in .NET?

For example, an excerpt from my mapping table

œ => oe
ž => z
Ÿ => Y
À => A
Á => A
 => A
à => A
Ä => AE

+4
source share
3 answers

If you really like to do this in one regex, there is a way to do it.

Dictionary<string, string> map = new Dictionary<string, string>() { {"œ","oe"}, {"ž", "z"}, {"Ÿ","Y"}, {"À","A"}, {"Á","A"}, {"Â","A"}, {"Ã","A"}, {"Ä","AE"}, }; string str = "AAAœžŸÀÂÃÄZZZ"; Regex r = new Regex(@"[œžŸÀÂÃÄ]"); string output = r.Replace(str, (Match m) => map[m.Value]); Console.WriteLine(output); 

Result

 AAAoezYAAAAEZZZ 
+4
source

I don't know an easy way to do this with regex (not sure if this is possible), but there is a clean way to do this:

 var replaceChars = new Dictionary<string, string> { {"œ", "oe"}, {"ž", "z"} }; string s = "ždfasœ"; foreach (var c in replaceChars) s = s.Replace(c.Key, c.Value); Console.WriteLine(s); 
0
source

To replace a string, I simply iterate over them in the mapping table and use string.Replace on:

 foreach(var r in replacements.Values) { myString.Replace(r.Key, r); } 

Not the most productive, but if you do not have a large number of lines to go through it, it should be good enough :).

0
source

All Articles