帮助解析文件的行并替换子字符串

Pra*_*bhu 2 .net regex vb.net parsing file

我需要替换文件每行中的某些字符.文件未分隔,但每行都有固定格式.例如,我需要将5个问号替换为'x'.每行中需要替换的5个问号位于第10位.例如:

输入文件:

abdfg trr?????456
g?????dhs?????diu
eerrttyycdhjjhddd
Run Code Online (Sandbox Code Playgroud)

输出文件应该是:

abdfg trrxxxxx456
g?????dhsxxxxxdiu
eerrttyycdhjjhddd
Run Code Online (Sandbox Code Playgroud)

输出文件将作为不同的文件保存到特定位置

在VB.NET中执行此操作的最佳方法是什么(我对VB有点新,所以任何代码示例都会有帮助)?

Jas*_*own 5

一种可能的解决方案是使用StreamReader(通过ReadLine()方法)解析文件中的每一行.当您在每一行中读取时,您可以使用StreamWriter将原始行写出(通过WriteLine(String)方法),并进行一次调整.如果该行符合您的替换要求,您将使用String.Replace(String,String)方法替换替换字符串的旧字符串.

这是一个解决方案(使用上面的示例数据编译和测试).您仍然希望添加一些异常处理(至少,确保文件首先存在):

Public Shared Sub ReplacementExample(string originalFile, string newFile)

    ' Read contents of "oringalFile"
    ' Replace 5 ? characters with 5 x characters.
    ' Write output to the "newFile"
    ' Note: Only do so if the ? characters begin at position 10


    Const replaceMe As String = "?????"
    Const replacement As String = "xxxxx"

    Dim line As String = Nothing

    Using r As New StreamReader(originalFile)
        Using w As New StreamWriter(newFile)

            line = r.ReadLine()

            While Not line Is Nothing
                w.WriteLine(line.Substring(0, 9) + _
                            line.Substring(9).Replace(replaceMe, replacement))

                line = r.ReadLine()
            End While

        End Using
    End Using
End Sub
Run Code Online (Sandbox Code Playgroud)