这是问题所在:
代码:
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>
因此,当我运行代码时,它会显示带有1
的MsgBox。为什么只有1?为什么不是2和3?
我已将?
添加到.*
,但它仍然相同。
答案 0 :(得分:1)
由于您只显示了MatchCollection
中的第一项,因此您可以使用For Each
循环来显示所有项目:
For Each item In doregex
MsgBox(item.ToString)
Next
您可以通过多种方式组合项目,其中一项:
Dim result As String = String.Empty
For Each item In doregex
result = String.Format("{0} {1}", result, item)
Next
MsgBox(result)
答案 1 :(得分:1)
MatchCollection
包含多个项目,但您只是使用doregex(0)
检索第一个项目。使用循环来到其他人:
Dim doregex As MatchCollection = Regex.Matches(myregex, findtext)
For Each match As Match In doregex
MsgBox(match.ToString)
Next
修改强>
要组合这些值,请在使用它们之前将它们附加到循环中的String:
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(匹配)
答案 2 :(得分:0)
使用LINQ:
Dim text_box_text = "<hello>1</hello>" & vbLf & "<hello>2</hello>" & vbLf & "<hello>3</hello>"
Dim findtext As String = "(?<=<hello>)(.*?)(?=</hello>)"
Dim my_matches_1 As List(Of String) = System.Text.RegularExpressions.Regex.Matches(text_box_text, findtext) _
.Cast(Of Match)() _
.Select(Function(m) m.Value) _
.ToList()
MsgBox(String.Join(vbLf, my_matches_1))
此外,使用此代码,您不需要使用耗费资源的外观。将正则表达式更改为
Dim findtext As String = "<hello>(.*?)</hello>"
并使用.Select(Function(m) m.Groups(1).Value)
代替.Select(Function(m) m.Value)
。