使用正则表达式查找具有特定内容的 json

Find json with specific content using regular expression

我有以下包含 json 个对象的 txt 文件。

[2018-12-10 06:30:38]..再同步健康数据... 
[2018-12-10 06:30:44]JSON回调处理--->>> 同步运动数据 [2018-12-10 06:30:44]同步运动健康数据json:{  "day" : 10,  "items" : [  {  "activeTime" : 5,  "calory" : 0,  "distance" : 0,  "stepCount" : 0  },
{  "activeTime" : 0,  "calory" : 0,  "distance" : 0,  "stepCount" : 0  },  {  "activeTime" : 0,  "calory" : 0,  "distance" : 0,  "stepCount" : 0  }  ],  "month" : 12,  "startTime" : 0,
"timeSpace" : 15,  "totalActiveTime" : 81,  "totalCalory" : 0,  "totalDistance" : 0,  "StepCount" : 0,  "year" : 2018 }  
[2018-12-10 06:30:44]同步运动健康数据items.sise()=96 
[2018-12-10 06:30:38]..再同步健康数据... 
[2018-12-10 06:30:44]JSON回调处理--->>> 同步运动数据 [2018-12-10 06:30:44]同步运动健康数据json:{  "day" : 10,  "items" : [  {  "activeTime" : 5,  "calory" : 0,  "distance" : 0,  "stepCount" : 0  },
{  "activeTime" : 0,  "calory" : 0,  "distance" : 0,  "stepCount" : 0  },  {  "activeTime" : 0,  "calory" : 0,  "distance" : 0,  "stepCount" : 0  }  ],  "month" : 12,  "startTime" : 0,  "timeSpace" : 15,  "totalActiveTime" : 81,  "totalCalory" : 0,  "totalDistance" : 0,  "totalCount" : 0,  "year" : 2018 }  
[2018-12-10 06:30:44]同步运动健康数据items.sise()=96

到目前为止,我已经定义了以下提取 json 个对象的表达式。

json:.+?(?=\[2)

我只想提取一个 json 对象,其中包含名为“totalCount”的元素。我应该在我的实际表达中添加什么?

已发布的 txt 文件替换了 json 个对象的位置

[2018-12-10 06:30:44]JSON回调处理--->>> 同步运动数据 [2018-12-10 06:30:44]同步运动健康数据json:{  "day" : 10,  "items" : [  {  "activeTime" : 5,  "calory" : 0,  "distance" : 0,  "stepCount" : 0  },
{  "activeTime" : 0,  "calory" : 0,  "distance" : 0,  "stepCount" : 0  },  {  "activeTime" : 0,  "calory" : 0,  "distance" : 0,  "stepCount" : 0  }  ],  "month" : 12,  "startTime" : 0,  "timeSpace" : 15,  "totalActiveTime" : 81,  "totalCalory" : 0,  "totalDistance" : 0,  "totalCount" : 0,  "year" : 2018 }  
[2018-12-10 06:30:44]同步运动健康数据items.sise()=96
[2018-12-10 06:30:38]..再同步健康数据... 
[2018-12-10 06:30:44]JSON回调处理--->>> 同步运动数据 [2018-12-10 06:30:44]同步运动健康数据json:{  "day" : 10,  "items" : [  {  "activeTime" : 5,  "calory" : 0,  "distance" : 0,  "stepCount" : 0  },
{  "activeTime" : 0,  "calory" : 0,  "distance" : 0,  "stepCount" : 0  },  {  "activeTime" : 0,  "calory" : 0,  "distance" : 0,  "stepCount" : 0  }  ],  "month" : 12,  "startTime" : 0,
"timeSpace" : 15,  "totalActiveTime" : 81,  "totalCalory" : 0,  "totalDistance" : 0,  "StepCount" : 0,  "year" : 2018 }  
[2018-12-10 06:30:44]同步运动健康数据items.sise()=96 
[2018-12-10 06:30:38]..再同步健康数据... 

您可以更改您的正则表达式,

json:.+?(?=\[2)

到,

(?s)json:(?!.*json:.*totalCount.*).*?totalCount.*?(?=\[2)

实现你的 json 只匹配其中包含 totalCount 的那个。

这种否定前瞻 (?!.*json:) 确保先前的 json: 匹配在它看到字符串中的另一个 json: 时被放弃,因此它开始与最接近的匹配json: 而不是第一个。

Demo