【问题标题】:Using Regular expression in VBA在 VBA 中使用正则表达式
【发布时间】:2014-03-14 16:29:28
【问题描述】:

这是我用逗号分隔的文本格式的示例记录

901,BLL,,,BQ,ARCTICA,,,,

我需要更换,,, to ,,

我尝试过的正则表达式

  With regex
    .MultiLine = False
    .Global = True
    .IgnoreCase = False
    .Pattern="^(?=[A-Z]{3})\\,{3,}",",,"))$ -- error 

现在我想将 Line 从文件传递到正则表达式以更正记录,有人可以指导我解决这个问题吗?我对 VBA 很陌生

我想逐行读取文件传递给Regex

【问题讨论】:

    标签: regex vba vbscript


    【解决方案1】:

    查看您的原始模式,我尝试使用 .Pattern = "^\d{3},\D{3},,,",它适用于示例记录,与 3 个数字字符、3 个字母、、、

    在答案中,我使用了更通用的模式.Pattern = "^\w*,\w*,\w*,," 这也适用于示例和数学 3 个逗号,每个逗号前面有 0 个或多个字母数字字符,后跟第四个逗号。两种模式都要求从字符串的开头开始匹配。

    模式.Pattern = "^\d+,[a-zA-Z]+,\w*,," 也适用于样本记录。它将指定在第一个逗号之前应该有 1 个或更大的数字字符(并且只有数字字符),并且在第二个逗号之前应该有 1 个或多个字母(并且只有字母)。在第三个逗号之前可以有 0 个或多个字母数字字符。

    left 函数删除匹配中最右边的字符,即。生成 Regex.Replace 使用的字符串的最后一个逗号。

    Sub Test()
        Dim str As String
    
        str = "901,BLL,,,BQ,ARCTICA,,,,"
        Debug.Print
        Debug.Print str
    
        str = strConv(str)
        Debug.Print str
    End Sub
    
    Function strConv(ByVal str As String) As String
    
        Dim objRegEx As Object
        Dim oMatches As Object
        Dim oMatch As Object
    
        Set objRegEx = CreateObject("VBScript.RegExp")
        With objRegEx
            .MultiLine = False
            .IgnoreCase = False
            .Global = True
            .Pattern = "^\w*,\w*,\w*,,"
        End With
    
        Set oMatches = objRegEx.Execute(str)
        If oMatches.Count > 0 Then
            For Each oMatch In oMatches
                str = objRegEx.Replace(str, Left(oMatch.Value, oMatch.Length - 1))
            Next oMatch
        End If
        strConv = str
    
    End Function
    

    【讨论】:

      【解决方案2】:

      试试这个

      Sub test()
      
          Dim str As String
          str = "901,BLL,,,BQ,ARCTICA,,,,"
      
          str = strConv(str)
          MsgBox str
      
      End Sub
      
      Function strConv(ByVal str As String) As String
      
          Dim objRegEx As Object, allMatches As Object
          Set objRegEx = CreateObject("VBScript.RegExp")
      
          With objRegEx
              .MultiLine = False
              .IgnoreCase = False
              .Global = True
              .Pattern = ",,,"
          End With
      
          strConv = objRegEx.Replace(str, ",,")
      
      End Function
      

      【讨论】:

      • 谢谢!以及如何传递整个文件?逐行阅读!
      • @VijaykumarHadalgi 请参阅此link,它显示了如何逐行读取文本文件。
      • 并且正则表达式甚至用 2 个逗号替换最后 3 个逗号,它只能在 BLL 之后替换
      猜你喜欢
      • 2017-01-18
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 2020-09-14
      • 1970-01-01
      • 2016-01-13
      • 1970-01-01
      相关资源
      最近更新 更多