简体   繁体   中英

Parse a long string with a pattern

I would appreciate some assistance in a tricky task I have to complete.

I receive a long long string in a text file which look like this :

{"place":"1","points":"1783","pseudo":"player1"},
{"place":"2","points":"1675","pseudo":"player34"},
{"place":"3","points":"1671","pseudo":"player45"},

So this is a single string with about 3000 times the same pattern stuck together. (there are 3000 players)

I would need to parse this string to fill a simple structure like this

public struct RankedPlayer
{
    public string Pseudo;
    public int Place;
    public int Point;
}

I don't find a easy way to do this. I start to struggle with RegEx but I don't know if it's a right approach.

Seems like you're dealing with a simple JSON string. Use JSON parson james.newtonking.com - json , and simply get them as your object ...

Here's an example:

// Having this:
public struct RankedPlayer
{
   public string Pseudo;
   public int Place;
   public int Point;
}

// With this input
{"place":"1","points":"1783","pseudo":"player1"},
{"place":"2","points":"1675","pseudo":"player34"},
{"place":"3","points":"1671","pseudo":"player45"},

// You should do something like:
string input = // your input;
var list_of_players = input.Split(',');

foreach (var player in list_of_players) {
    RankedPlayer r = JsonConvert.DeserializeObject<RankedPlayer>(player);
    // Do something with it.
}

So, just use your Player structure.

Edit:

You can use the following for your regex: {.*?} matching. Basically match everything between the curly braces, in a non greedy way (the ? after the .* ).

You need to use JavaScriptSerializer try:

JavaScriptSerializer serializer = new JavaScriptSerializer();
List<RankedPlayer> myData = serializer.Deserialize<List<RankedPlayer>>(strData);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM