我想收集 Google Geolocation API 的响应:
{
"location": {
"lat": 37.42659,
"lng": -122.07266190000001
},
"accuracy": 658.0
}
我在使用 std::regex
填充子匹配时遇到困难:
#include <string>
#include <iostream>
#include <regex>
int main()
{
std::string json = "{ \"location\": { \"lat\": 37.42659, \"lng\": -122.07266190000001 }, \"accuracy\": 658.0 }";
std::string error = "error";
if( json.find( "location" ) == std::string::npos ){
std::cout << "ERROR" << std::endl;
}
if( error.find( "location" ) == std::string::npos ){
std::cout << "ERROR" << std::endl;
}
try
{
std::regex pieces_regex("{ \"location\": { \"(lat)\": *([0-9.-]*),.*(lng)\": *([0-9.-]*).*(accuracy)\": *([0-9.-]*).*");
std::smatch pieces_match;
if (std::regex_match(json, pieces_match, pieces_regex)) {
std::cout << json << '\n' << std::endl;
for (size_t i = 0; i < pieces_match.size(); ++i) {
std::ssub_match sub_match = pieces_match[i];
std::string piece = sub_match.str();
std::cout << " submatch " << i << ": " << piece << '\n';
}
}
}
catch( std::regex_error &e )
{
std::cout << "ERRor: " << e.what() << std::endl;
}
return 0;
}
观察:在 g++ 中使用 --std=c++11
或更高版本编译
使用 VIM 的正则表达式,我可以像魅力一样适合所有子匹配:
/{ "location": { "\(lat\)": *\([0-9.-]*\),.*\(lng\)": *\([0-9.-]*\).*\(accuracy\)": *\([0-9.-]*\).*
而且工作正常!
在 :substitute
命令上使用上述模式:
.s/{ "location": { "\(lat\)": *\([0-9.-]*\),.*\(lng\)": *\([0-9.-]*\).*\(accuracy\)": *\([0-9.-]*\).*/\1:\2 \3:\4 \5:\6/g
最佳答案
正如已经评论过的那样,使用正则表达式解析 JSON 并不是最好的主意。尽管如此,一个有效的正则表达式看起来像这样:
std::regex pieces_regex("\\{ \"location\": \\{ \"(lat)\": *([0-9.-]*),.*\"(lng)\": *([0-9.-]*).*\"(accuracy)\": *([0-9.-]*).*");
关于c++ - 使用 C++11 的 std::regex 填充子匹配时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39332121/