there is a string

"128728581": {"vehicleType": "vehicleType", "isAlive": true, "name": "name", "clanAbbrev": "", "team": 1, "events": {}, "isTeamKiller": false}, 

tried to do so

 @"""\d+""[^}]+" 

but the problem is that there is a closing bracket in the "events". as an option, did so

 @"""\d+""[^}]+[^}]+events[^,]+[^}]+" 

but just changing the string and the event will not work, how to do it right?

And one more question: you need to get from the same line a set of numbers at the beginning, did so

 string[] arr = reg.Match(parse).ToString().Split('"'); reg = new Regex(@"\d+"); foreach (string val in arr) { if (reg.IsMatch(val)) { id = int.Parse(val); break; } } 

but somehow not the best option (it seems to me).

The fact that this is JSON, I know that there are specials for parsing, but I need to pull out lines with the id I need from a large document, and then parse them.

P.s why the code tag does not work, I can not understand how to highlight the code?

  • @VladD, 2010 and there in the settings did not find .NET 4.5 only .NET 4.0. - cyber_ua

1 answer 1

Use the appropriate tool for the task. If you want to parse JSON, use a JSON parser. For example, JSON.NET .

Although modern regular expressions are Turing-complete, it is known that correctly (that is, taking into account all possible pitfalls) to parse recursive grammars on them is unreasonably difficult. Do it right, save hemorrhoids and time for more enjoyable things.


If you are lucky enough to work with .NET 4.5, there is a built-in JSON parser .

  • Yes, I just do not want to use the parser to search for a couple of lines and select id from them ... - cyber_ua
  • @cyber_ua: Make no mistake. Your task is not to “find a couple of lines”, but to “parse the JSON format”. Solve the problem adequately to the condition of the task itself. There are a bunch of boundary cases, such as spaces before / after a colon, escaped double quotes in a line, line breaks in unexpected places, etc. Do you really want to consider all this in your regular expression? - VladD
  • > If you are lucky enough to work with .NET 4.5, there is a built-in JSON parser. hm, trying to connect using System.Json; Writes such a name is missing. I have a net 4.5 - I made a mistake, I have some damn 4.5) - cyber_ua
  • @cyber_ua: did you connect System.Runtime.Serialization.dll? - VladD
  • one
    @cyber_ua: Hmm. And what version of Visual Studio? If 2012, just select the project type ".NET 4.5", should work. - VladD