如何解决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
返回一个布尔值,True
或 False
。
这意味着,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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。