[英]PHP Regex Negative Lookahead with enters
I'm trying to scrape a .JSON file however the returned file returns multiple JSON objects in 1 .json file, resulting in a invalid json file. 我正在尝试抓取.JSON文件,但是返回的文件在1个.json文件中返回多个JSON对象,从而导致无效的json文件。 I'm trying to solve this by adding a [ before the JSON file and a ] after the json file.
我正在尝试通过在JSON文件之后添加[并在JSON文件之后添加]来解决此问题。 Then using a regex to add comma at the right places.
然后使用正则表达式在正确的位置添加逗号。
This is the file before the regex 这是正则表达式之前的文件
[{"status":"success"}
{"values":{"cpu":26.5152886753948387,"ram":0.8452846061135513},"origin":"core","type":-1,"uuid":"0000-e8-de-27-176d10"}
{"values":{"cpu":25.5839236550189568,"ram":0.8452846061135513},"origin":"core","type":-1,"uuid":"0000-e8-de-27-176d10"}
]
I created the following regex: }(?!\\s,|\\s])
. 我创建了以下正则表达式:
}(?!\\s,|\\s])
。 The problem I have is that it is still adding a , after the last } even though it's followed by a ]. 我遇到的问题是,即使在最后一个}之后,它仍会添加一个,。
What I'm getting: 我得到的是:
[{"status":"success"},
{"values":{"cpu":26.5152886753948387,"ram":0.8452846061135513},"origin":"core","type":-1,"uuid":"0000-e8-de-27-176d10"},
{"values":{"cpu":25.5839236550189568,"ram":0.8452846061135513},"origin":"core","type":-1,"uuid":"0000-e8-de-27-176d10"},
]
Expected result: 预期结果:
[{"status":"success"},
{"values":{"cpu":26.5152886753948387,"ram":0.8452846061135513},"origin":"core","type":-1,"uuid":"0000-e8-de-27-176d10"},
{"values":{"cpu":25.5839236550189568,"ram":0.8452846061135513},"origin":"core","type":-1,"uuid":"0000-e8-de-27-176d10"}
]
Replace \\s
in your regex with \\s*
since \\s
will match a single space character where \\s*
would match zero or more space characters. 替换
\\s
在您的正则表达式用\\s*
由于\\s
将匹配单个空格字符,其中\\s*
将匹配零个或多个空格字符。
}(?!\s*[,\]])
$re = "/}(?!\\s*[,\\]])/m";
$str = "[{\"status\":\"success\"}\n\n{\"values\":{\"cpu\":26.5152886753948387,\"ram\":0.8452846061135513},\"origin\":\"core\",\"type\":-1,\"uuid\":\"0000-e8-de-27-176d10\"}\n\n{\"values\":{\"cpu\":25.5839236550189568,\"ram\":0.8452846061135513},\"origin\":\"core\",\"type\":-1,\"uuid\":\"0000-e8-de-27-176d10\"}\n\n]";
$subst = "},";
$result = preg_replace($re, $subst, $str);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.