Search Unity

extracting data from a string with certain pattern

Discussion in 'Scripting' started by CipherZero, Jan 16, 2014.

  1. CipherZero

    CipherZero

    Joined:
    Jul 10, 2013
    Posts:
    38
    Hello everyone
    As the topic suggests, I'm trying to extract data from a string. The string looks like this:
    {"data1", "data2", "data3", "data4", "data5" ,"data6"}\n

    From this sample, I would like to extract "data3" and "data4" and put them into 2 int respectively (the \n is a new line character).

    The content and length for each "data slots" is dynamic, which means I cannot extract them by locating the positions of these data in the string. Please be noted that I have no control on the format of the string.

    I believe using regular expression can solve the problem, but I have absolute zero knowledge about it. So I would like to ask for any ideas that can do the work.

    Any help would be greatly appreciated.
     
  2. Aeronaut

    Aeronaut

    Joined:
    Jul 12, 2013
    Posts:
    51
    Hmmm i would do it with String.Trim... like this:

    Code (csharp):
    1.  
    2.         string t = "{\"data1\", \"data2\", \"data3\", \"data4\", \"data5\" ,\"data6\"}\n{\"data1\", \"data2\", \"data3\", \"data4\", \"data5\" ,\"data6\"}\n{\"data1\", \"data2\", \"data3\", \"data4\", \"data5\" ,\"data6\"}\n";
    3.         t = t.TrimEnd('\n');
    4.  
    5.         foreach (string line in t.Split('\n'))
    6.         {
    7.             string[] fields = line.Trim('{', '}').Split(',');
    8.  
    9.             for (int i = 0; i < fields.Length; i++)
    10.             {
    11.                 Debug.Log("Field#" + i + "=" + fields[i].Trim('"', ' '));
    12.             }
    13.         }
    14.  
     
    Last edited: Jan 16, 2014
  3. CipherZero

    CipherZero

    Joined:
    Jul 10, 2013
    Posts:
    38
    Thank you for your answer first as I will leave my PC soon so I'm not able to test it, but this looks promising! :D

    I would like to know that
    Code (csharp):
    1. foreach (string line in t.Split('\n'))
    the t.Split('\n') is for multiple strings with the same format all stick together?
     
  4. jackmott

    jackmott

    Joined:
    Jan 5, 2014
    Posts:
    167
  5. CipherZero

    CipherZero

    Joined:
    Jul 10, 2013
    Posts:
    38
    Hey Aeronaut, thank you for your answer, that piece of code work perfectly fine!
    But I would like to ask one more question, why wouldn't it be working if I also trim these 2 characters:
    Code (csharp):
    1. '"', ' '
    in
    Code (csharp):
    1. string[] field = line.Trim('{', '}').Split(',');
     
  6. Aeronaut

    Aeronaut

    Joined:
    Jul 12, 2013
    Posts:
    51
    Yes, like in the example...

    It would be work too, but you will have a empty Space after and " before and after the field...