Vb.net 如何在VB、Net中解析文本文档以获取值?
我希望将此文本文件解析为字符串,以将其插入数据库 源文本文件被读取为以下字符串:Vb.net 如何在VB、Net中解析文本文档以获取值?,vb.net,parsing,text-files,Vb.net,Parsing,Text Files,我希望将此文本文件解析为字符串,以将其插入数据库 源文本文件被读取为以下字符串: Line of unwanted text Another line of unwanted data Timestamp: 1/1/10 12:00 PM ID: 1 Details: All data processed. Length will vary. 我只想读取Timestamp、ID和Details,并将它们放入单独的字符串中,以将它们插入到数据表中。什么是在:之后捕获所有内容的最佳方法?直到
Line of unwanted text
Another line of unwanted data
Timestamp: 1/1/10 12:00 PM
ID: 1
Details: All data processed. Length will vary.
我只想读取Timestamp、ID和Details,并将它们放入单独的字符串中,以将它们插入到数据表中。什么是在:之后捕获所有内容的最佳方法?直到行的末尾
Dim Details as String = TextFile.Substring(Message.IndexOf("Details:"), X)
假设你的文件是完美的。。。一种方法是:
Imports System.IO
Dim AllLines() As String = File.ReadAllLines(FilePath)
Dim DatasIndex As Int32 = -1
For i As Int32 = 0 To AllLines.Length - 1
If AllLines(i).StartsWith("T") OrElse AllLines(i).StartsWith("t") Then
If AllLines(i).ToUpper().StartsWith("TIMESTAMP: ") Then
DatasIndex = i
Exit For
End If
End If
Next
If DatasIndex > -1 Then
' Dim ReadDate As Date = Date.Parse(AllLines(DatasIndex).Substring(11))
' Dim ReadID As Int32 = Integer.Parse(AllLines(DatasIndex + 1).Substring(4))
Dim ReadDate As String = AllLines(DatasIndex).Substring(11)
Dim ReadID As String = AllLines(DatasIndex + 1).Substring(4)
Dim ReadDetails As String = AllLines(DatasIndex + 2).Substring(9)
' send to database
End If
您没有说明
时间戳:
、ID:
和详细信息:
字符串的顺序始终相同,每个属性名称后都有一个尾随空格。如果必须使用字符串作为输入,可以使用字符串。拆分将其拆分为行,并处理每行<代码>字符串。子字符串
可用于提取行的其余部分-我刚刚硬编码了下面的起始位置
Dim timestamp As String = Nothing
Dim id As String = Nothing
Dim details As String = Nothing
For Each line In input.Split({vbCrLf, vbCr, vbLf}, StringSplitOptions.None)
If line.StartsWith("timestamp:", StringComparison.OrdinalIgnoreCase) Then
timestamp = line.Substring(10).Trim()
ElseIf line.StartsWith("id:", StringComparison.OrdinalIgnoreCase) Then
id = line.Substring(3).Trim()
ElseIf line.StartsWith("details:", StringComparison.OrdinalIgnoreCase) Then
details = line.Substring(8).Trim()
End If
Next
如果您可以更改读取数据的方式,那么循环可以是:
For each line In File.ReadLines("your\file\name.txt")
...
Next
把一行读到一个集合中,然后再看一遍集合……它们应该总是以相同的顺序排列,但我喜欢这样的想法,即通过不假设这一点来提供一些未来的证明。