以最快的方式替换文件中的特殊字符?

Replacing special characters in files in the fastest way possible?

我有一些文件包含特殊字符,如 é,ã,Δ,Ù 等。我想将它们替换为 NCR(十六进制)4 位值。我尝试了以下方法,但不确定它是否是实现我目标的最快方法...

var entities = new[]
{
new { ser = "\u00E9", rep = @"é" },
new { ser = "\u00E3", rep = @"ã" },
new { ser = "\u00EA", rep = @"ê" },
new { ser = "\u00E1", rep = @"á" },
new { ser = "\u00C1", rep = @"Á" },
new { ser = "\u00C9", rep = @"É" },
new { ser = "\u0394", rep = @"Δ" },
new { ser = "\u03B1", rep = @"α" },
new { ser = "\u03B2", rep = @"β" },
new { ser = "\u00B1", rep = @"±" },
//... so on
};

var files = Directory.GetFiles(path, "*.xml");
foreach (var file in files)
{
    string txt = File.ReadAllText(file);

    foreach (var entity in entities)
    {
        if (Regex.IsMatch(txt, entity.ser))
        {
            txt = Regex.Replace(txt, entity.ser, entity.rep);
        }
    };
    File.WriteAllText(file, txt);
}

有没有更快更有效的方法?

根据评论,您希望将 Unicode 字符(例如 Ù)替换为其 Unicode 值 (Ù)。 Regex.Replace 可能是实现此目标的最佳方法。

这是处理文件的循环:

var files = Directory.GetFiles(path, "*.xml");
foreach (var file in files)
{
    string txt = File.ReadAllText(file);

    string newTxt = Regex.Replace(
        txt,
        @"([^\u0000-\u007F]+)",
        HandleMatch);

    File.WriteAllText(file, newTxt);
}

这是匹配评估器:

private static char[] replacements = new[]
{
    'ø',
    'Ù'
};

private static string HandleMatch(Match m)
{
    // The pattern for the Regex will only match a single character, so get that character
    char c = m.Value[0];

    // Check if this is one of the characters we want to replace
    if (!replacements.Contains(c))
    {
        return m.Value;
    }

    // Convert the character to the 4 hex digit code
    string code = ((int) c).ToString("X4");

    // Format and return the code
    return "&#x" + code;
}

在循环中,只需要读入文件一次,然后Regex.Replace方法会处理输入中所有实例的替换。正则表达式的模式将匹配不在 0x00 - 0x7f 范围内的所有内容,这将是前 255 个字符(ASCII 字符)。

如果您只需要替换特定的 Unicode 字符,则需要构建这些字符的列表,并根据该列表检查 HandleMatch() 函数中 'c' 的值。

性能评价: 您正在尝试对一组文件执行选择性字符替换。至少,您必须将每个文件读入内存,然后检查每个字符以查看它是否符合您的条件。

一个更高效的选项可能是构建一个字符查找table,然后是每个字符的替换字符串。需要权衡的是,如果您有大量需要替换的字符,table 很快就会难以维护。您还保留了替换 table 中出现错误的风险,这将需要更多工作才能找到。