Microsoft VBS 正则表达式访问查询

问题描述

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

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

我在替换函数中使用了一个公共函数来完成任务,但我的模式没有按预期工作。访问查询条件和 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 返回一个布尔值,TrueFalse

这意味着,Replace 的名称如下:

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

将返回以下内容:

"JOHN DOE,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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...