2

I am trying to match square brackets i.e. [] in regex VBA in excel. I am trying with the below code but it is not working.

 Public Function IsSpecial(s As String) As Long
    Dim L As Long, LL As Long
    Dim sCh As String
    IsSpecial = 0
    For L = 1 To Len(s)
        sCh = Mid(s, L, 1)
        If sCh Like "[0-9a-zA-Z/;@%,'‚.+&/\(): ]" Or sCh = "_" Or sCh Like "[-]" Or sCh Like "\[" Then
        Else
            IsSpecial = 1
            Exit Function
        End If
    Next L
End Function
newbie0007
  • 47
  • 6

1 Answers1

2

According to Using the Like operator and wildcard characters in string comparisons:

You can use a group of one or more characters (charlist) enclosed in brackets ([ ]) to match any single character in expression, and charlist can include almost any characters in the ANSI character set, including digits. You can use the special characters opening bracket ([), question mark (?), number sign (#), and asterisk (*) to match themselves directly only if enclosed in brackets. You cannot use the closing bracket (]) within a group to match itself, but you can use it outside a group as an individual character.

So, you need to use

Ch Like "[[]"

However, the function you have is not following your logic, since it checks each char individually, and you want to make sure [] is checked as a char sequence.

With a regex, it will look like

Public Function IsSpecial(s As String) As Long
    Dim L As Long, LL As Long
    Dim rx As New regExp
    rx.Pattern = "^(?:[0-9a-zA-Z/;@%,'‚.+&/\\(): _-]|\[])*$"
    IsSpecial = 0
    If Not rx.Test(s) Then IsSpecial = 1
End Function
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563