Microsoft Access的 LIKE语句中的字符列表的右方括号
右方括号不能被包含在方括号内,因此在字符列表(charlist)中也不能使用,例如:
Like "*[#?]]*"
是否还有其他方法将右方括号插入到字符列表中,而不需要单独添加,就像这样:
Like "*[#?]*" Or Like "*]*"
解决方案
在正则表达式中,右方括号 ] 可以通过在其前面加上反斜杠 \ 来转义,因此 \] 匹配 ]。但正则表达式的文档不再更新,这点让人怀疑,例如:https://learn.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/scripting-articles/ms974570(v=msdn.10)?redirectedfrom=MSDN 。它是否已被弃用?
下面是一个示例函数:
Public Function REMatch(Fld As Variant, Pattern As String) As Boolean
'References: Microsoft VBScript Regular Expressions C:\Windows\SysWOW64\vbscript.dll\2
'If IsNull(Fld) Then Exit Function
If Fld <> "" Then
Else: Exit Function
End If
Static RE As RegExp
'Static RE As Object
Dim str As String
If RE Is Nothing Then
Set RE = New RegExp
'Set RE = CreateObject("VBScript.RegExp")
With RE
.IgnoreCase = True
.Global = True
.Multiline = True
.Pattern = Pattern
End With
End If
str = Nz(Fld)
REMatch = RE.Test(str)
End Function
Private Sub test_it()
MsgBox REMatch("abc]de", "[#\?\]]")
' Text CharList
End Sub
(' 在这里不能作为代码块中的注释标记)
也许可以写得更好。这样的自定义函数在查询中比直接使用 Like 语句慢得多。
备选方案
如前所述,Like 运算符存在不足,它不能像正则表达式那样工作。它的语法也略有不同。
你可以做的是定义一个实用函数并使用它:
Sub test()
If ContainsAnyChar("bla ] bla bla", "?#]") Then
MsgBox "Found!"
End If
End Sub
Function ContainsAnyChar(text As String, chars As String) As Boolean
Dim i As Long
For i = 1 To Len(chars)
If InStr(1, text, Mid(chars, i, 1), vbTextCompare) > 0 Then
ContainsAnyChar = True
Exit Function
End If
Next i
ContainsAnyChar = False
End Function
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。