开发者

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


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


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


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 :).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜