簡體   English   中英

批量替換文本文件中多個字符串的最佳方法是什么

[英]what is the best way to batch replace multiple strings in a text file

我有這個文件,有許多字符串和許多替換,我想用他們的替換品替換字符串,然后保存文本文件,這是我嘗試過,它做了一個糟糕的工作,但:

StreamReader sr = new StreamReader(fullPath + "\\DICT_J.txt", Encoding.Unicode);
            string cdID;
            string str;
            while (sr.Peek() >= 0)
            {
                string[] temp = sr.ReadLine().Split('^');
                if (temp.Length == 3)
                {
                    cdID = temp[1];
                    str = temp[2];
                    File.WriteAllText(path, Regex.Replace(File.ReadAllText(path), str, cdID), Encoding.Unicode);
                }
            }
            sr.Close();
            sr.Dispose();

這里 (抱歉,我不能在這里發布,因為SOF不允許Line返回)是包含替換的文件的示例,這里是模板:Line ID ^ Replacement ^ String要替換

不確定這是否有幫助,但這些是我的猜測。 這些方法有其他的編碼重載,我在這里沒有使用,但在你的情況下可能會有用。

1.用替換文件中的LineID替換原始文件上的字符串

public void Replace(string originalFile, string replacementsFile)
{
    var originalContent = System.IO.File.ReadAllLines(originalFile);
    var replacements = System.IO.File.ReadAllLines(replacementsFile);

    foreach(var replacement in replacements)
    {
        var _split = replacement.Split(new char[] { '^' });

        var lineNumber = Int32.Parse(_split[0]);

        // checks if the original content file has that line number and replaces
        if (originalContent.Length < lineNumber)
            originalContent[lineNumber] = originalContent[lineNumber].Replace(_split[1], _split[2]);
    }

    System.IO.File.WriteAllLines(originalFile, originalContent);
}

2.將替換模板的每個匹配替換為另一個文件

public void Replace(string originalFile, string replacementsFile)
{
    var originalContent = System.IO.File.ReadAllText(originalFile);
    var replacements = System.IO.File.ReadAllLines(replacementsFile);

    foreach(var replacement in replacements)
    {
        var _split = replacement.Split(new char[] { '^' });

        originalContent = originalContent.Replace(_split[1], _split[2]);
    }

    System.IO.File.WriteAllText(originalFile, originalContent);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM