Read something after a C#keyword

Asked

Viewed 71 times

3

I have the following situation, I have a document(txt) that has some things 'filled' type:

Nome:"João"; Idade:"20"; Estado:"SC";

The result I wanted is that the variables had only what is written between the quotes after each keyword.

string Nome; //Receberia João

int Idade; //Receberia 20

string Estado; //Receberia SC

NOTE: This document is generated in a single line by another program, I would like to use this to fill some fields automatically.

  • Is there a possibility to leave this TXT in JSON format? If yes, it would be much easier with the Newtonsoft

  • Ronaldo Araújo Alves, the file extension is . info but all ways to open show as if it were a txt

1 answer

1


Use the regular expression [^\\s;\\\"]+\\\"[^\\\"]+\\\" to pick up the kind of tickets <identificador>:<valor>.

Separate <identificador> of <valor> with String.Split(':'); and put them in a dictionary where the key is <identificador> and the value is <valor>.

From the dictionary it gets easier. You can popular variables, classes, vectors,... any way you want.

In the Repl.it

using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;

public class Analisador
{
   public static Dictionary<string,string> Parse(string entrada)
   {
     Dictionary<string,string> resultado =new Dictionary<string,string>();
      MatchCollection matches = Regex.Matches(entrada, "[^\\s;\\\"]+\\\"[^\\\"]+\\\"");      
      foreach (Match match in matches)
      {
        string[] arr = match.Value.Split(':'); 
        resultado.Add(arr[0], arr[1].Replace("\"", ""));
      }
      return resultado;
   }

   public static void Main()
   {
      Dictionary<string,string> Valores = Parse("Nome:\"João\"; Idade:\"20\"; Estado:\"SC\";");      

      foreach(var item in Valores)
      {
        Console.WriteLine($"{item.Key} = {item.Value}");
      }
   }
}
  • Thanks Augusto Vasques, I created a separate project to test your code and it worked perfectly, I will try to implement it in my project but thanks even for your help:)

  • I managed to implement and it worked but I still do not understand very well this thing of dictionaries for this purpose, you could indicate me a place to better understand?

  • https://docs.microsoft.com/pt-br/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.8

  • Very simple example using the Values dictionary : String nome = Valores["Nome"]; Console.WriteLine("O nome é " + nome);

Browser other questions tagged

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