Wildcard search of dictionary

前端 未结 4 1723
無奈伤痛
無奈伤痛 2020-12-11 21:23

After searching google and SO, I see that there is a way for me to search a dictionary for an existing key:

dict.exists(\"search string\")

4条回答
  •  借酒劲吻你
    2020-12-11 22:08

    The Dictionary Items method returns an array of all the items. You can Join those into a big string then use Instr() to determine if your search string is in the big string.

    From your example, you have the asterisk at the end, so I'm assuming you care how an item starts, not that a sub-string exists anywhere. So I look for delimiter+substring and add the delimiter to the front of the Join (for the sake of the first item). If you have different requirements, you'll have to adjust, but the theory is the same.

    I used two pipes as a delimiter because it's unlikely to be in the data and return a false positive. That may not be appropriate for your data.

    Public Function WildExists(ByRef dc As Scripting.Dictionary, ByVal sSearch As String) As Boolean        
        Const sDELIM As String = "||"        
        WildExists = InStr(1, sDELIM & Join(dc.Keys, sDELIM), sDELIM & sSearch) > 0        
    End Function
    

    test code

    Sub Test()
    
        Dim dc As Scripting.Dictionary            
        Set dc = New Scripting.Dictionary
    
        dc.Add "Apple", "Apple"
        dc.Add "Banana", "Banana"
        dc.Add "Pear", "Pear"
    
        Debug.Print WildExists(dc, "App") 'true
        Debug.Print WildExists(dc, "Ora") 'false
    
    End Sub
    

提交回复
热议问题