繁体   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