c++ - 使用 C++11 的 std::regex 填充子匹配时遇到问题

标签 c++ regex c++11

我想收集 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/

相关文章:

c++ - 显式实例化类模板中的自动构造函数

c++ - 什么时候应该使用 std::thread::detach?

c++ - 使用 guest 对象更改类中构​​造函数的调用顺序

python - ksh 风格的左右字符串剥离匹配的表达式?

c++ - std::string 和字符串文字之间的不一致

regex - 匹配前后没有字母的所有数字字符

mysql - 使用 Regex 解析 Bash 脚本中的 ClamAV 日志以插入 MySQL

c++ - 具有可变参数模板的数据结构

c++ - std::tuple get() 成员函数

c++ - C++ 中的正则表达式和双反斜杠