简体   繁体   English

正则表达式替换 - 多个字符

[英]Regex Replace - Multiple Characters

I have 20 or so characters that I need to replace with various other characters in a block of text. 我有20个左右的字符,我需要用一个文本块中的各种其他字符替换。 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? 或者在.NET中有更简单的方法吗?

For example, an excerpt from my mapping table is 例如,我的映射表的摘录是

œ => oe œ=> oe
ž => z ž=> z
Ÿ => Y Ÿ=> Y.
À => A À=> A.
Á => A Á=> A.
 => A Â=> A.
à => A Ã=> A.
Ä => AE Ä=> 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: 对于字符串替换,我只是在映射表中迭代这些并在它们上使用string.Replace:

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 :). 不是最高性能,但如果你没有很多字符串可以通过它应该是足够好:)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM