如何查找字符并替换文本文件中的整行

时间:2013-08-16 04:22:21

标签: vb.net

我如何进入文本文件找到某个角色然后替换该角色所在的整行?

以下是文本文件的示例:

    line1
    example line2
    others
    ......
    ....
    id: "RandomStr"
    more lines
    ...

我需要找到"id"的行并替换它。 编辑后的文本文件应为:

    line1
    example line2
    others
    ......
    ....
    "The correct line"
    more lines
    ...

2 个答案:

答案 0 :(得分:2)

首先,您需要阅读文本文件的每一行,如下所示:

For Each line As String In System.IO.File.ReadAllLines("PathToYourTextFile.txt")

Next

接下来,您需要搜索要匹配的字符串;如果找到,则将其替换为替换值,如下所示:

Dim outputLines As New List(Of String)()
Dim stringToMatch As String = "ValueToMatch"
Dim replacementString As String = "ReplacementValue"

For Each line As String In System.IO.File.ReadAllLines("PathToYourTextFile.txt")
    Dim matchFound As Boolean
    matchFound = line.Contains(stringToMatch)

    If matchFound Then
        ' Replace line with string
        outputLines.Add(replacementString)
    Else
        outputLines.Add(line)
    End If
Next

最后,将数据写回文件,如下所示:

System.IO.File.WriteAllLines("PathToYourOutputFile.txt", outputLines.ToArray(), Encoding.UTF8)

答案 1 :(得分:1)

首先将该行与正则表达式匹配。然后,如果匹配成功,则输出新行。我不知道VB.net,但C#中的函数类似于:

void replaceLines(string inputFilePath, string outputFilePath, string pattern, string replacement)
{
    Regex regex = new Regex(pattern);

    using (StreamReader reader = new StreamReader(inputFilePath))
    using (StreamWriter writer = new StreamWriter(outputFilePath))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            if (regex.IsMatch(line))
            {
                writer.Write(replacement);
            }
            else
            {
                writer.Write(line);
            }
        }
    }
}

然后你会这样称呼:

replaceLines(@"C:\temp\input.txt", @"c:\temp\output.txt", "id", "The correct line");

希望这会有所帮助。