angel
angel

Reputation: 9

how do you get a substring inside another text?

I have this text format:

name:
last name:
birthday:
years old:
parent:
school:

And i have next information..

name:name1
last name:lastname1
birthday:13/03/1991
years old:20
parent:fatherx
school:university x

How do I get:

name1
lastname1
13/03/1991
20
fatherx
university x

...for different variables? dont forget user sometime they dont have a information for example they have empty

parent:

Upvotes: 0

Views: 155

Answers (2)

agent-j
agent-j

Reputation: 27913

You can use the following code to create a dictionary of key-value pairs.

     List<string> fields = new List<string>
     {
        "name:",
        "last name:",
        "birthday:",
        "years old:",
        "parent:",
        "school:",
     };
     string rawData =
        @"name:angel rodrigo
last name:uc ku
birthday:13/03/1991
years old:20
parent:fernando uc puc
school:university x";

     var data = 
        fields.ToDictionary(
           field => field.TrimEnd (':'),
           field => Regex.Match(rawData, "(?<=" + Regex.Escape(field) + ").*"));
     foreach (var kvp in data)
     {
        Console.WriteLine(kvp.Key + "  =>  " + kvp.Value);
     }

Produces this result:

name  =>  angel rodrigo
last name  =>  uc ku
birthday  =>  13/03/1991
years old  =>  20
parent  =>  fernando uc puc
school  =>  university x

Upvotes: 1

George Johnston
George Johnston

Reputation: 32258

Split on the colon. For example, if you had each one of your lines stored in a seperate string, you could do the following e.g.

string s = "name:angel rodrigo";
string name= s.Split(':')[1];  // Get everything after the colon

Upvotes: 2

Related Questions