使用VB6,如何检查子字符串是否位于另一个字符串的开头?

使用VB6,如何检查子字符串是否位于另一个字符串的开头?,vb6,pattern-matching,Vb6,Pattern Matching,我需要浏览一个文本文件,检查每行的开头是否以“Attribute”开头。我应该如何在VB6中执行此操作 Dim sInput As String, check as Boolean check = true Open "myfile" For INPUT As #txtFile While Not EOF(txtFile) Input #txtFile, sInput If Not Mid(sInput,1,9) = "ATTRIBUTE" Then check = f

我需要浏览一个文本文件,检查每行的开头是否以“Attribute”开头。我应该如何在VB6中执行此操作

Dim sInput As String, check as Boolean
check = true
Open "myfile" For INPUT As #txtFile
While Not EOF(txtFile)
   Input #txtFile, sInput
   If Not Mid(sInput,1,9) = "ATTRIBUTE" Then
       check = false
   End if
   sInput = ""
Wend
Close #txtFile

如果结尾处的check=true,则所有行都以“ATTRIBUTE”开头,否则就不会了。

您可以尝试类似的方法(代码未测试)-

Dim ParseDate,alllinessstartwithattribute,fso,fs
AllLinesStartWithAttribute=False
设置fso=CreateObject(“Scripting.FileSystemObject”)
设置fs=fso.OpenTextFile(“c:\yourfile”,1,True)
直到fs.AtEndOfStream
如果左(fs.ReadLine,9)“属性”,则
AllLinesStartWithAttribute=False
退出Do
如果结束
环
财政司司长:结束
设置fs=Nothing

运行代码后,如果
alllinessstartwithattribute
值设置为true,则文件中的所有行都以“Attribute”开头。请注意,此代码区分大小写

使用正则表达式。您必须在引用中包含VBScript正则表达式库

Dim reg As new Scripting.Regex().
reg.Pattern = "^Attribute"
If reg.Match(line) Then
     ' Do Something
End If

您可以在类/模块的开头使用“Option Compare Text”使其不区分大小写。然后您可以使用类似“Attribute*”的运算符—使代码更具可读性。当您发现某些行无效时,您可以提前终止循环:)不建议发布在“Option Explicit”打开时不会编译的代码,或者是一种很好的做法。@Matt-公平点,代码现在已经整理完毕。add将使用
Option Explicit
打开进行编译。与您的两个相同。如果你想展开并澄清问题,请展开它,而不是开始一个全新的问答线程。你需要一个
UCase()
round
Mid(sInput,1,9)
,这样才能工作
Dim reg As new Scripting.Regex().
reg.Pattern = "^Attribute"
If reg.Match(line) Then
     ' Do Something
End If
Dim fso As New FileSystemObject
Dim ts As TextStream
Dim str As String

Set ts = fso.OpenTextFile(MyFile)
Do While Not ts.AtEndOfStream
    str = ts.ReadLine
    If InStr(str, "Attribute") = 1 Then
        ' do stuff
    End If
Loop