.net 在新行上匹配字符串?
因此,我一直在查看.NET中的.net 在新行上匹配字符串?,.net,string,.net,String,因此,我一直在查看.NET中的File.ReadAllText函数,并找到了如何搜索文本文件以匹配字符串的方法,但是 如何按每行搜索?例如,假设我有一个文本文件,如下所示 Names HarryS1 HarryS2 HarryS3 当然,我可以使用类似于: Dim text As String = File.ReadAllText("names.txt") Dim index As Integer = text.IndexOf(HarryS)
File.ReadAllText
函数,并找到了如何搜索文本文件以匹配字符串的方法,但是
如何按每行搜索?例如,假设我有一个文本文件,如下所示
Names
HarryS1
HarryS2
HarryS3
当然,我可以使用类似于:
Dim text As String = File.ReadAllText("names.txt")
Dim index As Integer = text.IndexOf(HarryS)
If index >= 0 Then
MessageBox.Show("Name Found")
Else
MessageBox.Show("Name not found")
End If
然而,它总是说它被找到了,因为HarryS在文本文件中存在不止一次。-我是否需要使用正则表达式来搜索字符串?或者我可以让它检查每行的基数吗?上面写着text.IndexOf(HarryS)。它不应该说text.IndexOf(“HarryS”)吗?无论如何,根据您的性能和灵活性要求,有很多方法可以实现您的目标。在您的情况下,最简单的检查是:
Try
Dim text As String = vbCrLf & System.IO.File.ReadAllText("C:\Temp\names.txt") & vbCrLf
Dim index As Integer = text.IndexOf(vbCrLf & "HarryS2" & vbCrLf)
If index >= 0 Then
MessageBox.Show("Name Found")
Else
MessageBox.Show("Name not found")
End If
Catch ex As Exception
MessageBox.Show("Exception found!" & vbCrLf & ex.ToString)
End Try
如果您需要进一步的灵活性,我能想到的实现这类功能的最有效方法是通过LINQ和正则表达式。来源:
概要
这里的FileOpen
功能打开文件路径,其中包含参数和编号1
的键引用。这是引用文件数据或文件的任何其他事务的关键。然后变量found
用于确认文件中的查找。接下来,我们使用While循环从文件中获取数据。这里的函数LineInput(1)
是您的答案,以字符串数据类型逐行从文件中获取数据。然后我们可以像比较字符串一样比较数据,并在整个文件中搜索匹配项。当我们找到匹配项时,我们更改变量found=True
的值。然后在循环之后,我们创建另一个比较,以确保找到并抛出带有消息框的响应。最后,FileClose
函数关闭文件
Imports System
Imports System.IO
Imports System.Text
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
Try
If File.Exists(path) Then
File.Delete(path)
End If
Dim sw As StreamWriter = New StreamWriter(path)
sw.WriteLine("This")
sw.WriteLine("is some text")
sw.WriteLine("to test")
sw.WriteLine("Reading")
sw.Close()
Dim sr As StreamReader = New StreamReader(path)
Do While sr.Peek() >= 0
Dim text As String = sr.ReadLine()
Dim index As Integer = text.IndexOf(HarryS)
If index >= 0 Then
MessageBox.Show("Name Found")
Else
MessageBox.Show("Name not found")
End If
Loop
sr.Close()
Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString())
End Try
End Sub
End Class
Try
FileOpen(1, "FilePath", OpenMode.Input, OpenAccess.Read, OpenShare.LockWrite)
Dim found As Boolean = False
While (EOF(1) = 0)
Dim readData As String = LineInput(1)
If readData = "HarryS" Then
found = True
Exit While
End If
End While
If found = True Then
MsgBox("Found")
Else
MsgBox("Not found")
End If
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Critical, "Error")
Finally
FileClose(1)
End Try