Consulting

Results 1 to 2 of 2

Thread: regexp to find multiple instances of the same structure term?

  1. #1
    VBAX Regular
    Joined
    Mar 2021
    Posts
    8
    Location

    regexp to find multiple instances of the same structure term?

    I have a string (filename, actually), that I want to see how many instances there are of XNNNN and/or XNNNNN, where N is a numerical digit.

    For example, if filename is "N1234 and N22522 - Content", then I would like to know that there are 2 matches and be able to analyze the 2 matches.

    I have it working for a single match, as follows:


        Dim nNumberPattern As String
        nNumberPattern = "(N[0-9]{3,}).*Content(s?).*"
        Dim nNumberMatches
        Dim nNumber As String
        
        With nNumberRegEx
            .Global = True
            .Pattern = nNumberPattern
        End With
            
        ' Let's find the n-number that we are working with (using the file's name)
        If nNumberRegEx.Test(myWorksheetObj.Parent.Name) Then
            Set nNumberMatches = nNumberRegEx.Execute(myWorksheetObj.Parent.Name)
            nNumber = nNumberMatches(0).SubMatches(0)
    How can I adapt this to identify that there are 2 matches when filename is "N1234 and N22522 - Content" and then be able to read/access/use each of "N1234" and "N22522"?

  2. #2
    Knowledge Base Approver VBAX Wizard p45cal's Avatar
    Joined
    Oct 2005
    Location
    Surrey UK
    Posts
    5,844
    Even though you have .Global set to TRUE, it will still only find one match because of the .*Content(s?).* bit of the pattern; your file name will only have one of those bits, so there will only be one match.
    Remove that end bit from the pattern and you'll have both/all your matches.
    I don't know regex well enough to suggest a search pattern that will return those matches and ensure that the filename contains Contents after the matches; maybe check for that independently in another line of code (Instr, InstrRev, Find, Search, etc.).
    You'll be able to run through the matches with the likes of
    For Each nNumberMatch In nNumberMatches
      MsgBox nNumberMatch.Value
    Next nNumberMatch
    Last edited by p45cal; 03-27-2021 at 03:37 AM.
    p45cal
    Everyone: If I've helped and you can't be bothered to acknowledge it, I can't be bothered to look at further posts from you.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •