Getting multiple values from a String

Asked

Viewed 51 times

2

Is there any way to get the arguments like in the example below, in a separate variable? I’m creating a language, and this is an example block:

for 0 to 250 step 50
^^^ ^ ^^ ^^^ ^^^^ ^^

Then I used the method String.Split(" ") and it worked, but the doubt is, and if you want to put a field that has spaces, example:

if "esse campo tem espaços" = true
^^ ^^^^^^^^^^^^^^^^^^^^^^^^ ^ ^^^^

but you’re returning like this:

if "esse campo tem espaços" = true
^^ ^^^^^ ^^^^^ ^^^ ^^^^^^^^ ^ ^^^^

Instead of getting an array like this:

if
esse campo tem espaços
=
true

He’s separating what’s in the field too, then he’s like this:

if
esse
campo
tem 
espaços
=
true

and conflict... There is some way to get the values within the field without this occurring?

1 answer

2


It may not be possible to use the method String.Split() for that purpose, regular expressions may fall well in this case, use the method Regex.Split():

Imports System.Text.RegularExpressions
'

Function ExtrairBlocos(ByVal texto As String) As List(Of String)
    Dim blocos As New List(Of String)
    blocos = Regex.Split(texto, "(""[^""]*""|\s+)").ToList()
    blocos.RemoveAll(Function(bloco) String.IsNullOrWhiteSpace(bloco))
    Return blocos
End Function

And to use, do:

Sub Main()
    Dim texto As String = "if ""esse campo tem espaços"" = true"
    Dim blocos As New List(Of String)
    blocos = ExtrairBlocos(texto)

    For Each bloco As String In blocos
        Console.WriteLine("{0}", bloco)
    Next
    Console.ReadLine()
End Sub

See demonstração

Browser other questions tagged

You are not signed in. Login or sign up in order to post.