【发布时间】:2020-05-02 12:32:52
【问题描述】:
我有一个看起来像这样的日志文件:
2019-12-24 18:00:17.8105|DEBUG|--------------------------------
https://...
2019-12-24 18:00:17.8105|DEBUG|Key: xxxxxxxxxxxxxxxxxxxxxxxx
{
"Id": "xxxxxxx",
"Times": "2019-12-24",
"Data": {
"Id": 8,
"Code": "5",
"Description": "abc",
},
"Number": 1,
...
}
2019-12-24 18:00:17.8105|DEBUG|--------------------------------
https://...
2019-12-24 18:00:17.8105|DEBUG|Key: xxxxxxxxxxxxxxxxxxxxxxxx
{
"Id": "xxxxxxx",
"Times": "2019-12-24",
"Data": {
"Id": 6,
"Code": "3",
"Description": "def"
},
"Number": 3,
...
}
//...and it repeats several times in this file with diferent data
我的目标是只获取“{ ... }”中的部分并将其添加到对象数组中并像
Array:
[
{"Id": "xxxxxxx", "Times": "2019-12-24", "Data": { "Id": 8, "Code": "5", "Description": "abc"}}
{"Id": "xxxxxxx", "Time": "2019-12-24", "Data": { "Id": 6, "Code": "3", "Description": "def"}}
]
到目前为止我所拥有的:
我知道我可以使用File 对象来读取文件,所以在我的 index.cshtml 中我放了:
@{
var result = "";
Array log = null;
var dataFile = Server.UrlPathEncode("C:/Temp/test.log");
if (File.Exists(dataFile))
{
log = File.ReadAllLines(dataFile);
if (log == null)
{
result = "The file is empty.";
}
}
else
{
result = "The file does not exist.";
}
}
但我不知道如何获取大括号内的内容并转换为对象
注意事项:
- 我正在使用 APS.NET mvc。
- 如果可能,我更喜欢使用正则表达式
- 数据是动态的,可以转换文件
更新:
获取我所做的 .log 文件的一部分:
foreach (var item in log)
{
text += item;
}
Regex regex = new Regex(@"(?={)[^}]*(?=})", RegexOptions.IgnoreCase);
matches = regex.Matches(text);
但是这个正则表达式并没有得到我想要的,它只得到"Description": "abc",},我还想得到"Number": ...
我使用this link 来输入正则表达式
有人可以帮忙处理正则表达式吗?
【问题讨论】:
标签: c# regex asp.net-mvc