Excel VBA正则表达式替换丢失一个字符

时间:2018-05-09 02:43:03

标签: regex excel-vba vba excel

以下代码匹配并替换,但捕获组旁边的数字将被使用。我哪里错了?

Sub test()
    Dim regex As Object 'Regexp object.
    Set regex = CreateObject("VBScript.RegExp") 'Regexp object.
    Dim strPattern As String: strPattern = "\d(AM|PM)" 'Declare regex pattern.
    Dim strReplace As String 'Placeholder string for replace operation.
    Dim target As String

    target = "1:05PM"

    strReplace = " $1"

    With regex
        .Global = True
        .IgnoreCase = False
        .Pattern = strPattern
    End With

    If regex.test(target) Then
        Debug.Print regex.Replace(target, strReplace)
    End If
End Sub

输出:

1:0 PM

1 个答案:

答案 0 :(得分:1)

这是因为你的正则表达式中有一个未捕获的\ d。尝试将{()放在each' from DeleteTriggers8.rb:106:in周围,即\d

您还需要将strReplace更改为(\d)(AM|PM)