5

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 a single 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 is

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

Chris Cudmore
  • 29,793
  • 12
  • 57
  • 94
jchohan
  • 51
  • 1
  • 2
  • would you really use Regex.Replace(), or you can accept any solution, like string.replace("à", a)? – serhio Dec 22 '09 at 15:49

3 Answers3

4

If you really like to do it in single regex, there is way to do that.

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
YOU
  • 120,166
  • 34
  • 186
  • 219
0

I'm not aware of an easy way to do it using regex(not sure it is possible) but here is a clean way to do it:

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);
Yuriy Faktorovich
  • 67,283
  • 14
  • 105
  • 142
0

For string replacement, I'd just iterate through these in your mapping table and use string.Replace on them:

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

Not the most performant, but if you don't have a lot of strings to go through it should be good enough :).

Nicolas Webb
  • 1,312
  • 10
  • 22