我在vb.net中使用了一个regex,我想将所有符合条件的textbox1逐行输出到textbox2,这就是我正在使用的。
textbox1(Sorce) textbox2(Result)
123kaadd234 123,234
fjalj787fafkajl34ddfa999 787,134,999
我的代码:
Imports System.Text.RegularExpressions
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim pattern As String = "d{3}"
For row As Int16 = 0 To TextBox1.Lines.Count - 1
Dim input As String = TextBox1.Lines(row)
Dim m As MatchCollection = Regex.Matches(input, pattern)
For i As Int16 = 0 To m.Count - 1
TextBox2.Text = TextBox2.Text & m(i).ToString & "," & vbCrLf
Next
Next
End Sub
End Class
首先,第二行应该产生787,999
,因为在34
之前没有1
(有一个字母l
(。
代码的其余部分可以使用进行修复
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim pattern As String = "d{3}"
For row As Int16 = 0 To TextBox1.Lines.Count - 1
Dim input As String = TextBox1.Lines(row)
Dim line As String = String.Join(",", Regex.Matches(input, pattern).Cast(Of Match)().Select(Function(m) m.Value).ToList())
TextBox2.AppendText(line & vbCrLf)
Next
End Sub
注:
Regex.Matches(input, pattern).Cast(Of Match)().Select(Function(m) m.Value).ToList()
将所有匹配值收集到一个列表中String.Join(",", ...)
将列表合并为一个逗号分隔的字符串TextBox2.AppendText(line & vbCrLf)
将新行追加到多行文本框控件中