There is a string.

"name":"dog" 

The easiest option is to pull out of it what comes after the name to make a regular session

 (?<=name":").+?(?=") 

Everything basically works, but the file is large and the regulars slow down very much. Are there alternatives for this operation?

  • four
    you apparently json wound up. You can look in this direction - Trymount
  • Json deserialize a very expensive operation, since it is large. Easier to do as it is - Rajab
  • How big? - isnullxbh
  • Parsing complex languages ​​like JSON, regulars, or even worse, manual is always a bad idea. - VladD
  • 3
    If you have a huge file, and you only need to extract some of the information, try JsonTextReader . - VladD

1 answer 1

Manual analysis of complex formats is not the easiest thing. You may have a lot of problems. Offhand: spaces? comments? string constants? different types of quotes? You do not want to provide for all this yourself? Therefore, it makes sense to use a ready-made parser, for example, JSON.NET.

If parsing an entire file into memory is too expensive, then you can instead parse its tokens in streaming mode. Here's an example of how to pull out all the values ​​of the string name attributes:

 using Newtonsoft.Json; class Test { public static void Main() { string json = "{ 'everything' : [ " + "{ 'name': 'dog' }, " + "{ 'trap': '\"name\" : \"snake\"' }, " + "{ \"name\" : \"elephant\"}]}"; // вам нужен будет, скорее всего, не StringReader, а StreamReader using (TextReader sr = new StringReader(json)) { foreach (var name in ExtractNames(sr)) Console.WriteLine(name); } } static IEnumerable<string> ExtractNames(TextReader tr) { using (var jsr = new JsonTextReader(tr)) { bool expectValue = false; while (jsr.Read()) { if (jsr.TokenType == JsonToken.Comment) continue; if (expectValue) { if (jsr.ValueType == typeof(string)) yield return (string)jsr.Value; expectValue = false; } else { if (jsr.TokenType == JsonToken.PropertyName && (string)jsr.Value == "name") expectValue = true; } } } } } 
  • and if the Name property is on an object with the name property? for example: { 'name': { 'name': { 'name': 'dog' } } } all three will be displayed? - Grundy
  • @Grundy: Nah, only string values ​​are taken. if (jsr.ValueType == typeof(string)) ... - VladD
  • aha, that is, returns only internal? and on nesting of restriction is not present after all? - Grundy
  • @Grundy: Yeah, just internal. It looks just a pair of tokens "attribute name" / "beginning attribute value", so there should not be any problems with nesting. - VladD
  • no - this is what question is the answer? :-D managed to edit! - Grundy