Search code examples
vbavb-like-operator

Use Like operator to check for one or two digit numbers


How do you use the Like operator to see if a number is a one or two digit number? I can use # or ## but how do I check for numbers that may be between 0-99? The below example does not work:

str = "ab12cd
debug.print str Like "ab[0-99]cd

I am trying to do a more complex Like to check something similar to below where the numbers may be one or two digits:

str = "Local_Buffer.O[3].7"
debug.print str Like "*.O[[][0-99][]].[0-99]

A few of these patterns I'm trying to detect will have multiple 1-2 digit numbers and I'd like to avoid something like below

str = "Local_Buffer.O[3].7"
debug.print str Like "*.O[[]#[]].#" OR str Like "*.O[[]#[]].##" OR str Like "*.O[[]##[]].#" or str Like "*.O[[]##[]].##"

Solution

  • I agree with taller about the use of RegExp.
    Try something like:

    Sub test()
        Dim reg 'As New VBScript_RegExp_55.RegExp 'Assuming corresponding reference has not been activated => use of CreateObject instead
        Dim str As String
        
        Set reg = CreateObject("VBScript.RegExp")
        reg.Pattern = ".*\.O\[\d{1,2}\]\.\d{1,2}$"
        
        str = "Local_Buffer.O[3].7"
        Debug.Print reg.Test(str)
    End Sub
    

    Note: I'm not sure I've correctly understood the expected pattern wrt "[]" so you might have to adjust the pattern in my example.