vb.net textfile split by line to combobox
test
cool
username: username1
username: username2
username: username3
username: username4
username: username5
test
I want to extract all 5 username in add combobox
You could read the lines into an array, and then use a Regex
to match the username lines.
Start with putting:
Imports System.IO
Imports System.Text.RegularExpressions
in the top of your code file, then you can use this code:
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
The Regex
is a class which is capable of matching substrings according to the specified pattern.
The pattern I used can be explained like this:
(?<=username\\:\\s).+
(?<=username\\:
: Match a line starting with username:
.
\\s
: Match a space character (after username:
).
.+
: Match any character combination after that (which is your username, and what will be returned from m.Value
).
Online code test: http://ideone.com/xnVkCc
Read more about Regex: MSDN - .NET Framework Regular Expressions
Hope this helps!
EDIT:
If you want to match both username:
and user name:
you could try declaring the Regex
with the following pattern instead:
Dim RgEx As New Regex("(?<=user(?:\s)?name\:\s).+", RegexOptions.IgnoreCase)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.