Microsoft VBS 正则表达式访问查询

Microsoft VBS Regex Access Query

我正在尝试从存储在 MS Access 查询列中的文本字符串替换 SSN。评论字段是自由文本,我需要用 XXX-XX-XXXX 替换标准 SSN(即 123-45-6789)。

例如,我希望“JOHN DOE,111-11-1111 REWARD 6 DOL 已生成。提交选择应在 07-FEB-35 之前完成,请遵守”成为“JOHN DOE,XXX-XX” -XXXX 奖励 6 DOL 已生成。提交选择应在 07-FEB-35 之前完成,请遵守

我在替换函数中使用了 Public 函数来完成任务,但我的模式没有按预期工作。访问查询条件和 RegexMathc 函数:

Expr1: Replace([Comments],RegexMatch([Comments],"\d{3}\-\d{2}\-\d{4}"),"XXX-XX-XXXX")

Public Function RegexMatch(value As Variant, pattern As String) As Boolean
    If IsNull(value) Then Exit Function
    ' Using a static, we avoid re-creating the same regex object for every call '
    Static regex As Object
    ' Initialise the Regex object '
    If regex Is Nothing Then
        Set regex = CreateObject("vbscript.regexp")
        With regex
            .Global = False
            .IgnoreCase = False
            .Multiline = False
            
        End With
    End If
    ' Update the regex pattern if it has changed since last time we were called '
    If regex.pattern <> pattern Then regex.pattern = pattern
    ' Test the value against the pattern '
    RegexMatch = regex.Test(value)
End Function

当我在 regex101 中尝试正则表达式模式时,它发现 SSN 字符串没有问题,但它不在我的访问查询列中。

您的 RegexMatch returns 布尔值,TrueFalse

也就是说,Replace 是这样称呼的:

Replace("JOHN DOE,111-11-1111, True reward", True, "XXX-XX-XXXX")

将返回以下内容:

"JOHN DOE,111-11-1111, XXX-XX-XXXX reward"

您需要在一个函数中进行匹配和替换:

Public Function RegexReplace(value As Variant, Pattern As String, Replace As String) As String
    If IsNull(value) Then Exit Function
    ' Using a static, we avoid re-creating the same regex object for every call '
    Static regex As Object
    ' Initialise the Regex object '
    If regex Is Nothing Then
        Set regex = CreateObject("vbscript.regexp")
        With regex
            .Global = True 'We want to replace all occurrences
            .IgnoreCase = False
            .MultiLine = False
            
        End With
    End If
    ' Update the regex pattern if it has changed since last time we were called '
    If regex.Pattern <> Pattern Then regex.Pattern = Pattern
    ' Replace using the pattern
    RegexReplace = regex.Replace(value, Replace)
End Function