查看您的原始模式,我尝试使用 .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