std regex_search to match only current line

前端 未结 2 1719
Happy的楠姐
Happy的楠姐 2021-01-24 16:49

I use a various regexes to parse a C source file, line by line. First i read all the content of file in a string:

ifstream file_stream(\"commented.cpp\",ifstream         


        
2条回答
  •  野性不改
    2021-01-24 17:03

    #include //comment

    The code should fail, my logic is with those options to regex_search, the match should fail, because it should search for pattern in the first line:

    #include

    But instead it searches whole string, and immideatly finds //comment. I need help, to make regex_search match only in current line.

    Are you trying to match all // comments in a source code file, or only the first line?

    The former can be done like this:

    #include 
    #include 
    #include 
    
    int main()
    {
      auto input = std::ifstream{"stream_union.h"};
    
      for(auto line = std::string{}; getline(input, line); )
      {
        auto submatch = std::smatch{};
        auto pattern = std::regex(R"(//)");
        std::regex_search(line, submatch, pattern);
    
        auto match = submatch.str(0);
        if(match.empty()) continue;
    
        std::cout << line << std::endl;
      }
      std::cout << std::endl;
    
      return EXIT_SUCCESS;
    }
    

    And the later can be done like this:

    #include 
    #include 
    #include 
    
    int main()
    {
      auto input = std::ifstream{"stream_union.h"};
      auto line = std::string{};
      getline(input, line);
    
      auto submatch = std::smatch{};
      auto pattern = std::regex(R"(//)");
      std::regex_search(line, submatch, pattern);
    
      auto match = submatch.str(0);
      if(match.empty()) { return EXIT_FAILURE; }
    
      std::cout << line << std::endl;
    
      return EXIT_SUCCESS;
    }
    

    If for any reason you're trying to get the position of the match, tellg() will do that for you.

提交回复
热议问题