using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
string filePath = "yourLargeFile.txt";
var result = new Dictionary<string, Dictionary<string, string>>();
using (StreamReader reader = new StreamReader(filePath))
{
string line;
Regex jsonRegex = new Regex(@"^\{ ""id"":""(\d+)"", ""name"":""([^""]+)"", ""value"":""([^""]+)""\}$");
while ((line = reader.ReadLine()) != null)
{
Match match = jsonRegex.Match(line);
if (match.Success)
{
string id = match.Groups[1].Value;
string name = match.Groups[2].Value;
string value = match.Groups[3].Value;
if (!result.ContainsKey(id))
{
result[id] = new Dictionary<string, string>();
}
result[id]["name"] = name;
result[id]["value"] = value;
}
}
}
// 打印结果验证
foreach (var kvp in result)
{
Console.WriteLine($"Id: {kvp.Key}, Name: {kvp.Value["name"]}, Value: {kvp.Value["value"]}");
}
}
}
- 文件读取:使用
StreamReader
逐行读取文件,避免一次性加载整个文件到内存。
- 正则表达式验证:定义正则表达式
^\{ ""id"":""(\d+)"", ""name"":""([^""]+)"", ""value"":""([^""]+)""\}$
来验证JSON片段格式,确保id
是数字,name
和value
是非空字符串。
- 数据存储:使用
Dictionary<string, Dictionary<string, string>>
来存储提取的数据,外层字典键为id
,内层字典包含name
和value
的键值对。
- 性能优化:逐行读取和处理,减少内存占用,同时正则表达式预编译提高匹配效率。