Stefan Đorđević Stefan Đorđević - 6 months ago 15
Vb.net Question

Regex matching first occurance only?

So, this is the problem:

Code:

Dim findtext As String = "(?<=<hello>)(.*?)(?=</hello>)"
Dim myregex As String = TextBox1.Text
Dim doregex As MatchCollection = Regex.Matches(myregex, findtext)
MsgBox(doregex(0).ToString)


TextBox1:

<hello>1</hello>
<hello>2</hello>
<hello>3</hello>


So, when i run the code, it shows MsgBox with
1
. Why only 1? Why not 2 and 3?

I added
?
to
.*
, but it's still the same.

Xen Xen
Answer

The MatchCollection contains multiple items but you are only retrieving the first one with doregex(0). Use a loop to get to the others:

    Dim doregex As MatchCollection = Regex.Matches(myregex, findtext)
    For Each match As Match In doregex
        MsgBox(match.ToString)
    Next

EDIT:

To combine the values, append them to a String within the loop before you use it:

    Dim doregex As MatchCollection = Regex.Matches(myregex, findtext)
    Dim matches As String = ""  ' consider StringBuilder if there are many matches
    For Each match As Match In doregex
        matches = matches + match.ToString + " " 
    Next
    MsgBox(matches)