【问题标题】:Structure replacement possible complex RegexReplace solution?结构替换可能复杂的 RegexReplace 解决方案?
【发布时间】:2019-10-29 16:07:50
【问题描述】:

我需要运行一个更改 CSV 文件结构的 VBScript。为了简单起见,我只使用了 3 个数据字段,但还有更多。在生产环境中,我将拥有一个包含数百行的 CSV 文件。

问题是所有内容都用双引号引起来。最终结果有时可能是没有引号或单引号,或者有时是三者的混合。

我完全不知道我应该如何处理这个问题,并且正在寻找一些指导。这看起来像是 RegexReplace 的工作,但因为它是混合的,我不知道如何开始。修改文件后,我必须在原始文件的顶部。

CSV 示例:
“苹果”;“12”;“xyz”
"somereallylongword";"7687";"therdfox"

模式
"%1";%2;'%3'

期望的结果
"苹果";12;'xyz'
"somereallylongword";7687;'therefox'

我想要实现的是能够制作一种新的模式类型。在我的例子中:
"%1" - 我保留原来的双引号。
%2 - 删除双引号。
'%3' - 将双引号替换为单引号。

任何见解将不胜感激。

【问题讨论】:

  • 可以看到所有数字和文本混合之间的区别,但不能看到引号。通常使用双引号来封装分隔符 (,) 和/或嵌入需要转义的引号 " this \"program\" is it"
  • 第二个元素%2总是一个数字?
  • 可悲的是,元素并不总是一个数字。它可以是任何东西。
  • @Cyber​​drac 请检查我的更新答案并告诉我这是否解决了您的问题?

标签: regex vbscript


【解决方案1】:

您可以使用 ADODB 读取 CSV 文件:

Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H1

Dim objConnection
Dim objRecordset
Dim sCSVFolder
Dim sCSVFile
Dim sValue

Set objConnection = CreateObject("ADODB.Connection")
Set objRecordset = CreateObject("ADODB.Recordset")

sCSVFolder = "C:\CSV_Folder\"
sCSVFile = "your_csv_file.csv"

objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
          "Data Source=" & sCSVFolder & ";" & _
          "Extended Properties=""text;HDR=YES;FMT=Delimited"""

objRecordset.Open "SELECT * FROM " & sCSVFile, _
          objConnection, adOpenStatic, adLockOptimistic, adCmdText

Do Until objRecordset.EOF
    ' Modify and write fields to new text file here
    sValue = objRecordset.Fields.Item("FieldName")
    objRecordset.MoveNext
Loop

通过这种方式,您可以让 ADO 处理读取数据并删除双引号,并且您可以轻松地将数据作为 Recordset 进行操作。

【讨论】:

    【解决方案2】:

    只需通过替换您的 CSV 文件的路径来尝试此代码并告诉我它在您这边是如何工作的?

    Option Explicit
    Dim Data
    Call ForceCScriptExecution()
    Data = ReadFile("C:\Test\Test.csv")
    wscript.echo "Before Replacing"
    wscript.echo String(50,"-")
    wscript.echo Data
    wscript.echo String(50,"-")
    wscript.echo "After Replacing"
    wscript.echo String(50,"-")
    wscript.echo Search_Replace(Data)
    wscript.echo String(50,"-")
    wscript.sleep 20000
    '-----------------------------------------------
    Function Search_Replace(Data)
        Dim oRegExp,strPattern1,strPattern2
        Dim strReplace1,strReplace2,strResult1,strResult2
        strPattern1 = ";(\x22)(\S+\w+)(\x22);"
        strReplace1 = ";$2;"
        strPattern2 = "[;]\x22([^\x22]+)\x22"
        strReplace2 = ";'$1'"
        Set oRegExp = New RegExp
        oRegExp.Global = True 
        oRegExp.IgnoreCase = True 
        oRegExp.Pattern = strPattern1
        strResult1 = oRegExp.Replace(Data,strReplace1)
        oRegExp.Pattern = strPattern2
        strResult2 = oRegExp.Replace(strResult1,strReplace2)
        Search_Replace = strResult2
    End Function
    '-----------------------------------------------
    Function ReadFile(path)
        Const ForReading = 1
        Dim objFSO,objFile
        Set objFSO = CreateObject("Scripting.FileSystemObject")
        Set objFile = objFSO.OpenTextFile(path,ForReading)
        ReadFile = objFile.ReadAll
        objFile.Close
    End Function
    '----------------------------------------------
    Sub ForceCScriptExecution()
        Dim Arg, Str, cmd, Title
        Title = "Search and Replace using RegExp by Hackoo 2019"
        cmd = "CMD /C Title " & Title &" & color 0A & Mode 80,30 & "
        If Not LCase( Right( WScript.FullName, 12 ) ) = "\cscript.exe" Then
            For Each Arg In WScript.Arguments
                If InStr( Arg, " " ) Then Arg = """" & Arg & """"
                Str = Str & " " & Arg
            Next
            CreateObject( "WScript.Shell" ).Run _
            cmd & "cscript //nologo """ & _
            WScript.ScriptFullName & _
            """ " & Str
            WScript.Quit
        End If
    End Sub
    '-----------------------------------------------
    

    编辑:批处理脚本代码

    您可以使用批处理脚本轻松完成,而无需使用 Regex:

    @echo off
    Title Edit CSV File
    Set "Input_CSV_File=C:\Test\Test.csv"
    Set "OutPut_CSV_File=C:\Test\OutPut_Test.csv"
    If Exist "%OutPut_CSV_File%" Del "%OutPut_CSV_File%"
    @for /f "tokens=1,2,3 delims=;" %%a in ('Type "%Input_CSV_File%"') Do (
        echo "%%~a";%%~b;'%%~c' 
        echo "%%~a";%%~b;'%%~c'>>"%OutPut_CSV_File%"
    )
    TimeOut /T 5 /NoBreak>nul
    If Exist "%OutPut_CSV_File%" Notepad "%OutPut_CSV_File%" & Exit
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-06
      • 1970-01-01
      • 1970-01-01
      • 2020-11-13
      • 1970-01-01
      • 2015-12-15
      • 1970-01-01
      • 2015-06-08
      相关资源
      最近更新 更多