This post is a continuation of a discuss that started here:
https://www.msofficeforums.com/word-...x-pattern.html
Batman1,
Replying to your:
"There is nothing that says that a number that has 4 or 5 digits has to be a word. So, it can be part of a word. Besides, your code will find 3452 in the string "a3452b" (and correctly), so it should find 12456 (1245 also meets the criteria, but we want the longest result possible) in the string "124567".
Besides, if data = "13452234567" the code will not find 34522"
Starting from your original challenge:
"Find in the sequence all numbers consisting of 4 or 5 digits, whose first 4 digits must have at least 1 digit 2"
1. I would not consider "13452234567" to be a number consisting of 4 or 5 digits. I consider that to be a number consisting of 11 digits and my original reply treated it as such.
2. There was nothing in my original reply that implied that the 4 or 5 digit numbers "had" to be a word.
3. Now if one wishes to find 34522 embedded in a larger sequence of numbers that is certainly possible.
4. If our goal is to find 34522 in 13452234567, then do we also want to A) find 45223, 52234, 22345 and 23456 which are also number segments embedded in the larger 11 digit string or B) Find the first match in the sequence and escape or C) Continue looking for matches in even longer strings e.g., "1345223456712345" and return both 34522 and 67123
Code:
Sub ScratchMacroA()
Dim oRng As Range
Set oRng = ActiveDocument.Range
With oRng.Find
.Text = "[0-9]{1,}"
.MatchWildcards = True
While .Execute
If InStr(Left(oRng.Text, 4), "2") > 0 Then
Select Case Len(oRng.Text)
Case Is > 4
Debug.Print Left(oRng.Text, 5)
Case Is = 4
Debug.Print oRng.Text
End Select
End If
oRng.End = oRng.Start + 1
Wend
End With
lbl_Exit:
Exit Sub
End Sub
Sub ScratchMacroB()
Dim oRng As Range
Set oRng = ActiveDocument.Range
With oRng.Find
.Text = "[0-9]{1,}"
.MatchWildcards = True
Do While .Execute
If InStr(Left(oRng.Text, 4), "2") > 0 Then
Select Case Len(oRng.Text)
Case Is > 4
Debug.Print Left(oRng.Text, 5)
Exit Do
Case Is = 4
Debug.Print oRng.Text
Exit Do
End Select
End If
oRng.End = oRng.Start + 1
Loop
End With
lbl_Exit:
Exit Sub
End Sub
Sub ScratchMacroC()
Dim oRng As Range
Set oRng = ActiveDocument.Range
Dim lngIndex As Long
With oRng.Find
.Text = "[0-9]{1,}"
.MatchWildcards = True
While .Execute
lngIndex = 1
If InStr(Left(oRng.Text, 4), "2") > 0 Then
Select Case Len(oRng.Text)
Case Is > 4
Debug.Print Left(oRng.Text, 5)
lngIndex = 5
Case Is = 4
Debug.Print oRng.Text
lngIndex = 4
End Select
End If
oRng.End = oRng.Start + lngIndex
Wend
End With
lbl_Exit:
Exit Sub
End Sub
For the RegEx proponents, what would the RegEx pattern be?