使用RegEx和c#解析字符串

本文关键字:字符串 RegEx 使用 | 更新日期: 2023-09-27 18:10:03

我有以下正则表达式-

 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'":之后写出所有的文本,这可能是一种可能的方法,任何帮助都是非常感谢的。

使用RegEx和c#解析字符串

您当然可以使用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。网络选择令牌

使用JSON。网络图书馆。

我会在c#中使用正则表达式你的表达式会像这样

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

如果你不知道文本的具体内容那么可能会像这样

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