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

时间:2011-07-19 19:20:52

标签: .net regex vb.net file parsing

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

输入文件:

abdfg trr?????456
g?????dhs?????diu
eerrttyycdhjjhddd

输出文件应为:

abdfg trrxxxxx456
g?????dhsxxxxxdiu
eerrttyycdhjjhddd

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

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:2)

根据提供的源代码位置判断为9

C#代码:

var res = s.Substring(0, 9) + s.Substring(9).Replace("?????", "xxxxx");

VB.NET:

Dim res As String = (s.Substring(0, 9) & s.Substring(9).Replace("?????", "xxxxx"))

示例VB.NET:

Using sr As StreamReader = New StreamReader("a.txt")
        Using sw As StreamWriter = New StreamWriter("b.txt")
            Dim line As String = Nothing
            Do While (Not line = sr.ReadLine Is Nothing)
                Dim res As String = (line.Substring(0, 9) & line.Substring(9).Replace("?????", "xxxxx"))
                sw.WriteLine(res)
            Loop
        End Using
    End Using

示例C#:

using (var sr = new StreamReader("a.txt"))
{
    using (var sw = new StreamWriter("b.txt"))
    {
        string line = null;
        while ((line = sr.ReadLine()) != null)
        {
            var res = line.Substring(0, 9) + line.Substring(9).Replace("?????", "xxxxx");
            sw.WriteLine(res);
        }
    }
}