PDA

View Full Version : regexp to find multiple instances of the same structure term?



SFRandy
03-26-2021, 02:24 PM
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"?

p45cal
03-27-2021, 03:03 AM
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