Std regex_search matches only the current line

I use various regular expressions to parse the source C file line by line. First I read the entire contents of the file in a line:

ifstream file_stream("commented.cpp",ifstream::binary);

std::string txt((std::istreambuf_iterator<char>(file_stream)),
std::istreambuf_iterator<char>());

Then I use a set of regular expressions, which should be applied continuously until it finds a match, here I will give only one example:

vector<regex> rules = { regex("^//[^\n]*$") };

char * search =(char*)txt.c_str();

int position = 0, length = 0;

for (int i = 0; i < rules.size(); i++) {
  cmatch match;

  if (regex_search(search + position, match, rules[i],regex_constants::match_not_bol | regex_constants::match_not_eol)) 
  {
     position += ( match.position() + match.length() );        
  }

}

But that will not work. It will correspond to the comment not in the current line, but it will search for the whole line for the first match regex_constants::match_not_boland regex_constants::match_not_eolshould make it regex_searchrecognize ^$only as the beginning / end of the line, and not end start / end of the entire block. So here is my file:

commented.cpp:

#include <stdio.h>
//comment

, regex_search, , :

#include <stdio.h>

//comment. , regex_search . match_not_bol match_not_eol . , , , , , , , regex .

+1
2

, , ,

, , .
, , std::regex.

: .


- , :

  • boost::regex Boost :

    • PCRE
    • ( )
    • bin ( )
    • , std::regex
  • gcc version 7.1.0 . , , 6.3.0

  • clang version 3

(= ) , , :

  • : std.regex :

  • PCRE pcre2 c

    • ,
  • Perl one-liner
+1

#include <stdio.h> //comment

, regex_search, , :

#include <stdio.h>

//. , regex_search .

// ?

:

#include <iostream>
#include <fstream>
#include <regex>

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;
}

:

#include <iostream>
#include <fstream>
#include <regex>

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;
}

- , tellg() .

0

Source: https://habr.com/ru/post/1685287/


All Articles