2011-09-30 113 views
0

我有以下的普通Expression-解析字符串C#

string s = "{\"data\": {\"words\": [{\"wordsText\": \"Three Elephants /d 
in the jungle\"}]}}"; 

    string[] words = s.Split('\\',':','[',']','{','}','"'); 
    foreach (string word in words) 
    { 
     Console.WriteLine(word); 
    } 

哪个输出 -

data 

words 

wordsText 

Three Elephants /d in the jungle 

什么是摆脱在输出前3行的最好的方式,使我只得到最后一行Three Elephants /d in the jungle

我相信如果我在"wordsText\":之后写出所有的文字,这可能是一种可能的方法,任何帮助都非常感谢。

回答

5

你可以肯定地使用RegEx,但由于看起来像JSON,你最好用JSON.NET来解析它。

JObject o = JObject.Parse(@"{ 
    ""Stores"": [ 
    ""Lambton Quay"", 
    ""Willis Street"" 
    ], 
    ""Manufacturers"": [ 
    { 
     ""Name"": ""Acme Co"", 
     ""Products"": [ 
     { 
      ""Name"": ""Anvil"", 
      ""Price"": 50 
     } 
     ] 
    }, 
    { 
     ""Name"": ""Contoso"", 
     ""Products"": [ 
     { 
      ""Name"": ""Elbow Grease"", 
      ""Price"": 99.95 
     }, 
     { 
      ""Name"": ""Headlight Fluid"", 
      ""Price"": 4 
     } 
     ] 
    } 
    ] 
}"); 

string name = (string)o.SelectToken("Manufacturers[0].Name"); 
// Acme Co 

decimal productPrice = (decimal)o.SelectToken("Manufacturers[0].Products[0].Price"); 
// 50 

string productName = (string)o.SelectToken("Manufacturers[1].Products[0].Name"); 
// Elbow Grease 

参见:Json.Net Select Token

它使用JSON.NET Library

+0

你是对的这是JSON,但是在.NET中使用什么库>因为它不承认JObject,我会标记为正确的。 – Ebikeneser

+0

@Jambo使用JSON.NET库。我用一个链接更新了问题。 –

+0

非常感谢。 – Ebikeneser

0

我会使用正则表达式在C#中您对此表现会是这样

MatchCollection matchCtrls = Regex.Matches(pageText, @"Th(.*)e", RegexOptions.Singleline); 

如果你不知道什么文本将是专门那么很可能是这样的

MatchCollection matchCtrls = Regex.Matches(pageText, @"": \(.*)\", RegexOptions.Singleline); 
+0

using System.Text.RegularExpressions; – CBRRacer