Reputation: 73
net with .net version 4.5 i have created a rich text file with the text
[username]lewis[password]foo[level]1[username]bob[password]hi[level]3
all on one line. I have a structure
Public Structure User
Dim username As String
Dim password As String
Dim Level As String
End Structure
I also have an array of this structure called users How would I load the text file into the users structure. I've tried using RegEx but it didn't go well so how would i split the text properly.
Upvotes: 0
Views: 218
Reputation: 17001
Dim line As String = "[username]lewis[password]foo[level]1[username]bob[password]hi[level]3"
Dim parts1() As String = line.Split({"["c}, StringSplitOptions.RemoveEmptyEntries)
For Each part1 As String In parts1
Dim parts2() As String = part1.Split("]"c)
Dim key As String = parts2(0)
Dim value As String = parts2(1)
Debug.WriteLine(key & " = " & value)
Next
Key
will be the string inside the square brackets, and Value
will be the string that follows it. You can do a case / select
off of key to put the value in to the correct member of your structure. This will easily let you add more fields or change their order.
Keep in mind that this will fail if the username or password contains square brackets. If you want to allow those you will have to specially encode them.
Upvotes: 0
Reputation: 755317
If the string is always of that format you could do something like the following
Dim line As String = GetNextLine()
Dim array = line.Split(new Char() { "["c, "]"c }, StringSplitOptions.RemoveEmptyEntries)
Dim user As new User()
user.username = array(1)
user.password = array(3)
user.level = array(5)
Upvotes: 1