How to return matched string all locations?

Steven Young 261 Reputation points
2022-11-25T06:10:54.07+00:00

My code is below
Dim a As String = "ABCD efabCd efcdfg"
Dim b As String = "cd"

    Dim i As Int32 = a.IndexOf(b, StringComparison.OrdinalIgnoreCase)  

There are 3 "cd" in the a string, how to return all index locations? I need to return "2, 9, 14", but the i only return "2".

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,929 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Steven Young 261 Reputation points
    2022-11-25T06:22:44.783+00:00
        Dim a As String = "ABCD efabCd efcdfg"  
        Dim b As String = "cd"  
    
        Dim rx = New Regex(b, RegexOptions.Compiled Or RegexOptions.IgnoreCase)  
        Dim match As Match = rx.Match(a)  
    
        Do While match.Success  
            MessageBox.Show(match.Value & ": " & match.Index)  
            match = match.NextMatch()  
        Loop  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.