2016-03-27 28 views
2

vb.net文本文件拆分,以組合框vb.net文本文件通過分割線組合框

test 
cool 
username: username1 
username: username2 
username: username3 
username: username4 
username: username5 
test 

我想提取的附加組合框的所有5名

+0

我已經編輯我的答案(看到底部)一個匹配'username:'和'user name:'的模式。 –

回答

2

,你可以讀取行到一個數組,然後使用Regex來匹配用戶名行。

開始投入:

Imports System.IO 
Imports System.Text.RegularExpressions 
在你的代碼文件的頂部

,那麼你可以使用此代碼:

Dim FileLines() As String = File.ReadAllLines("path to file") 'Read all the lines of the file into a String array. 

Dim RgEx As New Regex("(?<=username\:\s).+", RegexOptions.IgnoreCase) 'Declare a new, case-insensitive Regex. 
For Each Line As String In FileLines 'Loop through every line. 
    Dim m As Match = RgEx.Match(Line) 'Match the Regex pattern. 
    If m IsNot Nothing AndAlso m.Success = True Then 'Have we found a match? 
     ComboBox1.Items.Add(m.Value) 'Add the match to the ComboBox. 
    End If 
Next 

Regex是一類能夠根據匹配子的指定的模式。

我所用的圖案可以這樣解釋:

(?<=username\:\s).+

(?<=username\::匹配開始username:的線。

\s:匹配一個空格字符(在username:之後)。

.+:之後匹配任何字符組合(這是您的用戶名,以及將從m.Value返回的內容)。


在線測試代碼:http://ideone.com/xnVkCc

瞭解更多關於正則表達式:MSDN - .NET Framework Regular Expressions

希望這有助於!


編輯:

如果你想匹配username:user name:,你可以嘗試用下面的模式,而不是宣佈Regex

Dim RgEx As New Regex("(?<=user(?:\s)?name\:\s).+", RegexOptions.IgnoreCase)