简体   繁体   English

如何在文本文件中获取某个字符串

[英]How to get a certain string in a text file

Here's an example text file named "sample.txt": 这是一个名为“sample.txt”的示例文本文件:

This is a sample text file and I need to return this string > "myScript.sql".
And this another string: "myNewScript.sql"
How do I do it using VBScript?

And what I want to do is to return the "myScript.sql" and "myNewScript.sql" string using VB Script. 我想要做的是使用VB脚本返回“myScript.sql”和“myNewScript.sql”字符串。

Like: 喜欢:

If string's file extension =  ".sql"
  THEN
    myString = Scan left and get the string until the QUOTE (") symbol.
    Echo myString

Something like that. 这样的事情。

You can easily use regular expressions in this case: 在这种情况下,您可以轻松使用正则表达式:

Set objFSO = CreateObject("Scripting.FileSystemObject") 
Set file = objFSO.OpenTextFile("sample.txt" , ForReading)  
Const ForReading = 1

Dim re
Set re = new regexp 
re.Pattern = """(\w+?[.]sql)"""
re.IgnoreCase = True
re.Global = True

Dim line
Do Until file.AtEndOfStream
    line = file.ReadLine
    For Each m In re.Execute(line)
       Wscript.Echo m.Submatches(0)
    Next
Loop 

By executing it with: 通过以下方式执行:

cscript //nologo test.vbs

With the file sample.txt: 使用文件sample.txt:

This is a sample text file and I need to return this string > "myScript.sql".
And this another string: "myNewScript.sql"
How do I do it using VBScript?

You'll get this: 你会得到这个:

myScript.sql
myNewScript.sql
Option Explicit

Const ForReading = 1

Dim fso
    Set fso = WScript.CreateObject("Scripting.FileSystemObject")

Dim fileMatch
    With New RegExp
        .Pattern = """([^""]*\.sql)"""
        .IgnoreCase = True
        .Global = True
        For Each fileMatch in .Execute(fso.OpenTextFile("sample.txt", ForReading).ReadAll())
            WScript.Echo fileMatch.SubMatches(0)
        Next 
    End With

This will search the file contents for quoted strings that end in .sql , extracting the text inside the quotes 这将在文件内容中搜索以.sql结尾的引用字符串,从而提取引号内的文本

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM