kamyar
kamyar

Reputation: 39

How to extract a string by two diffrent split options?

I have a string which is a part of a text file. I need to extract data related to each item.
The string is:
GRID "G1 Global" LABEL "A 2 3" DIR "X-1" COORD 0 VISIBLE "Yes"
I used Split by "space" and "quotation marks" but the the resulats was not as I expected. I need to assign data to each item. For example "G1 Global" for GRID and 0 for COORD.
I used tis code for extract each word from the string:

    Dim linestring As Object
    Dim word0 As String
    Dim i As Integer
    Dim goalstring As String = TextBox2.Text 'Thextbox2.text = GRID "G1 Global"  LABEL "A 2 3"  DIR "X-1"  COORD 0 VISIBLE "Yes"
    'linestring = Split(goalstring, """")
    linestring = Split(goalstring, " ")
    For Each word0 In linestring
        If word0 <> "" Then
            i += 1
            Console.WriteLine(i & ":" & word0)
        End If
    Next

The expected result is:
1:GRID
2:G1 Global
3:LABEL
4:A 2 3
5:DIR
6:X-1
7:COORD
8:0
9:VISIBLE
10:"Yes"

But I get this by Split(goalstring, " "):
1:GRID
2:"G1
3:Global"
4:LABEL
5:"A
6:2
7:3"
8:DIR
9:"X-1"
10:COORD
11:0
12:VISIBLE
13:"Yes"

and this by Split(goalstring, """"):
1: GRID
2:G1 Global
3: LABEL
4:A 2 3
5: DIR
6:X-1
7: COORD 0 VISIBLE
8:Yes

Upvotes: 0

Views: 63

Answers (1)

David Wilson
David Wilson

Reputation: 4439

While it's absolutely fine to use regex expressions, personally I find the, obtuse and difficult to debug. I would rather write personal code - for example The code below iterates through each character of the string.

If it finds a character that isn't a space or a quote, it adds it to the word0.

If it finds a space, it writes word0 to the console.

If it finds a quote, it adds everything after the quote to word0 until it finds the next quote. It then writes word0 to the console.

Dim word0 As String = ""
Dim goalstring As String = TextBox2.Text
For i As Integer = 0 To goalstring.Length - 1
    Select Case goalstring(i)
        Case " "c
            Console.WriteLine(word0)
            word0 = ""
        Case """"c
            Do While goalstring(i + 1) <> """"
                i += 1
                word0 = word0 & goalstring(i)
            Loop
            Console.WriteLine(word0)
            i += 2
            word0 = ""
        Case Else
            word0 = word0 & goalstring(i)
    End Select
Next

If you want quotes around the last outputted line then you'll need to alter your code to add each word to a list instead of writing to the console. Then add quotes to the last item in the list and then write the list to the console.

Upvotes: 3

Related Questions