简体   繁体   中英

Parse string using RegEx and C#

I have the following Regular Expression-

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

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

Which outputs-

data

words

wordsText

Three Elephants /d in the jungle

What is the best way to get rid of the first 3 lines in the output so that I only get the last line- Three Elephants /d in the jungle .

I believe if I were to write out all text after "wordsText\\": this could be a possible method, any help is much appreciated.

You could use RegEx sure, but since that looks like JSON you would be better off using JSON.NET to parse that.

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

See: Json.Net Select Token

This uses the JSON.NET Library .

I would use the Regex in C# your expressions for that would be like this

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

If you don't know what the text is going to be specifically then probably something like this

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

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