Relative positions of substrings

I have to write a VBScript for a text in a paragraph to be searched for and find out the positions of the text from the last location.

Suppose, if the sentence is:

This is my first paragraph and my first try

and I am going to have to find out the position of "my", then the first position will be 9 and the second will be 32. But instead of printing 32, I have to print the next position from 9. When I execute this code, I get the result 9 and 32.

Dim X,i

For i=1 to 10
  X=Instr(i, "This is my first paragraph and my first try", "my", 1)

  i=X+1

  msgbox i
Next

What the problem is here is the For interval loop! I have to adjust the For loop per the text to be searched for. Can it be done using a constant interval? This will print values 9 and 32, but I need to print the latter value as 23.

Upvotes: 2

Views: 48

Answers (1)

Bond
Bond

Reputation: 16321

Here are a couple of options.

  1. Use a Do While loop:

    Const SOME_TEXT = "This is my first paragraph and my first try"
    
    Dim intPos, intLast
    intPos = InStr(1, SOME_TEXT, "my")
    
    Do While intPos > 0
        WScript.Echo intPos - intLast
        intLast = intPos
        intPos = InStr(intPos + 1, SOME_TEXT, "my")
    Loop
    
  2. Use a regex and take advantage of the FirstIndex property of the Match object:

    Dim re
    Set re = New RegExp
    re.Pattern = "\bmy\b"
    re.Global = True
    
    Dim m, i
    Set m = re.Execute("This is my first paragraph and my first try")
    
    For i = 0 To m.Count - 1
        If i = 0 Then MsgBox m(i).FirstIndex + 1 Else MsgBox m(i).FirstIndex - m(i-1).FirstIndex
    Next
    

Upvotes: 2

Related Questions