Get two values from a string

Asked

Viewed 113 times

1

I’m creating a programming language and for you to define variables in it you use this code:

def NomeDaVariavel = ValorDela;

And wanted to know how I only take the field Nome da variável, separate from the ValorDela.

Any ideas? Thank you.

Updating

If (Regex.IsMatch(currentText, "^\s*(def)")) Then
   Dim tempProvider As Match = Regex.Match(currentText, "^\s*def.*[^=]=")
   Dim nomeDaVariavel As String = tempProvider.Value.Substring(
              currentText.IndexOf("def") + Iff(currentText.Trim() = " = ", 4, 3)).Replace("=", "").Replace(" ", "")
   Dim valorDaVariavel As String = ParseStr(currentText)
   MsgBox(FX("A Variável '\0' tem o valor de '\1'.", nomeDaVariavel, valorDaVariavel))
   Continue For
End If

That worked because I tested it like this:

def testando = 'Olá, mundo!';

And it worked! Here’s the tip ;-)

1 answer

1


One can use the method String.Substring to extract part of the text.

Dim texto As String = "def NomeDaVariavel = ValorDela;"

Dim indiceVar As Integer = texto.IndexOf("def")
Dim indiceVal As Integer = texto.IndexOf("=")

Dim tamanhoVar As Integer = Len(indiceVar)

Dim varNome As String = texto.Substring(indiceVar + tamanhoVar, texto.IndexOf("=") - tamanhoVar - 1)
Dim varVal As String = texto.Substring(indiceVal + 2, texto.IndexOf(";") - indiceVal - 2)

Console.WriteLine(String.Format("{0} = {1}", varNome, varVal))
Console.ReadKey()

If you need to get each word, use the method String.Split:

Dim texto As String = "def NomeDaVariavel = ValorDela;"

Dim palavras As String() = texto.Split(New Char() {" "})
Dim palavra As String
For Each palavra In palavras
    Console.WriteLine(palavra)
Next
Console.ReadKey()

Exemplo

  • I liked this method, but there’s only her name, and the value?

  • 1

    @Cypherpotato I already added.

Browser other questions tagged

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