这是我用逗号分隔的文本格式的示例记录
901,BLL,,,BQ,ARCTICA,,,,
我需要替换,,, to ,,
我试过的正则表达式
With regex
.MultiLine = False
.Global = True
.IgnoreCase = False
.Pattern="^(?=[A-Z]{3})\\,{3,}",",,"))$ -- error
现在我想将Line从文件传递到Regex以更正记录,有些人可以指导我修复这个我对VBA来说很新鲜
我想逐行读取文件,将其传递给Regex
答案 0 :(得分:2)
查看原始模式我尝试使用.Pattern = "^\d{3},\D{3},,,"
作为样本记录,与3个数字字符,3个字母一样,
在答案中我使用了更广义的模式.Pattern = "^\w*,\w*,\w*,,"
这也适用于样本和数学3个逗号,每个逗号前面有0个或更多个字母数字字符,后面跟着第四个逗号。两种模式都需要匹配来自字符串的开头。
模式.Pattern = "^\d+,[a-zA-Z]+,\w*,,"
也适用于样本记录。它将指定在第一个逗号之前应该有1个或更多的数字字符(并且只有数字字符),并且在第二个逗号之前应该是1个或更多个字母(并且只有字母)。在第三个逗号之前,可能有0个或更多个字母数字字符。
左侧函数删除匹配中最右边的字符,即。最后一个逗号,用于生成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
答案 1 :(得分:1)
试试这个
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