簡體   English   中英

使用RegEx和C#解析字符串

[英]Parse string using RegEx and 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\\":之后寫出所有文本"wordsText\\":這可能是一種方法,那么任何幫助將不勝感激。

您可以肯定使用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選擇令牌

這使用JSON.NET庫

我會在C#中使用Regex,因此您的表達式將像這樣

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

如果您不知道具體的文字,則可能是這樣的

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM