Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
133 views
in Technique[技术] by (71.8m points)

c# regex? text string from file and sort into searchable array?

I Have the following text from a file:

{"players":[{"i":11,"p":0,"a":3186,"n":"IanHx","f":1,"ps":0,"pd":0,"bc":0},{"i":12,"p":0,"a":115,"n":"LoZtamnik","f":1,"ps":0,"pd":0,"bc":0},{"i":58,"p":0,"a":156,"n":"Mr701","f":2,"ps":0,"pd":0,"bc":0},{"i":59,"p":0,"a":156,"n":"B0NE4","f":2,"ps":0,"pd":0,"bc":0},{"i":64,"p":0,"a":324,"n":"5teveJ","f":1,"ps":0,"pd":0,"bc":0}],[.......

What i am trying to do is parse the text, to end up with a array for each bit of data between {...}

so final result would look like:

i=11
p=0
a=3186
n=IanHx
f=1
ps=0
pd=0
bc=0

then i can store these in a database

so far i have something like this:

string contents = System.IO.File.ReadAllText("local text file"); //load string contents with text file
Regex regex1 = new Regex(""players":\[(?<players>.*)\]"); //find the players section "players":[.......]
Match match1 = regex1.Match(contents); //load match1    
Regex regex2 = new Regex("{(?<player>([^}]*))}"); // then break down each player {....}
MatchCollection match2 = regex2.Matches(match1.Groups["players"].Value); //load match2 with each player

then i get stuck trying to split the match string[] somehow and looking at it may be overcomplicating it?

any pointer to an easier solution to the data parsing

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your far better off trying to deserialize this with Json.Net from NuGet

Define some classes to match your file structure:

public class Root
{
    public List<Something> players {get; set;}
}

public class Something
{
    public string i {get; set;}
    public string p {get; set;}
    public string a {get; set;}
    public string n {get; set;}
    public string f {get; set;}
    public string ps {get; set;}
    public string pd {get; set;}
    public string bc {get; set;}
}

use Json.Net to crunch:

var json = @"{""players"":[{""i"":11,""p"":0,""a"":3186,""n"":""IanHx"",""f"":1,""ps"":0,""pd"":0,""bc"":0},{""i"":12,""p"":0,""a"":115,""n"":""LoZtamnik"",""f"":1,""ps"":0,""pd"":0,""bc"":0},{""i"":58,""p"":0,""a"":156,""n"":""Mr701"",""f"":2,""ps"":0,""pd"":0,""bc"":0},{""i"":59,""p"":0,""a"":156,""n"":""B0NE4"",""f"":2,""ps"":0,""pd"":0,""bc"":0},{""i"":64,""p"":0,""a"":324,""n"":""5teveJ"",""f"":1,""ps"":0,""pd"":0,""bc"":0}]}";

var data = JsonConvert.DeserializeObject<Root>(json);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...