C++中的多行正则表达式

Multilines regex in C++

本文关键字:正则表达式 C++      更新时间:2023-10-16

实际上,我试图在多行字符串中找到正则表达式,但我认为我在新行(等于''(之后找到下一个正则表达式的方式是错误的。这是我的正则表达式:

#include <iostream>
#include <fstream>
#include <sstream>
#include <regex>
#define USE ".*[0-9]{2}\.[0-9]{2}\.[0-9]{2}\.[0-9]{2}\.[0-9]{2}.*(?:\n)*"
int                     main(int argc, char **argv)
{
  std::stringstream     stream;
  std::filebuf          *buffer;
  std::fstream          fs;
  std::string           str;
  std::regex            regex(USE);
  if (argc != 2)
    {
      std::cerr << "Think to the use !" << std::endl;
      return (-1);
    }
  fs.open(argv[1]);
  if (fs)
    {
      stream << (buffer = fs.rdbuf());
      str = stream.str();
      if (std::regex_match(str, regex))
        std::cout << "Yes" << std::endl;
      else
        std::cout << "No" << std::endl;
      fs.close();
    }
  return (0);
}
构造正

则表达式对象时可以指定一些标志,请参阅有关详细信息,文档 http://en.cppreference.com/w/cpp/regex/basic_regex。

带有正则表达式::扩展标志的简短工作示例,其中在搜索中指定了换行符 '':

#include <iostream>
#include <regex>
int main(int argc, char **argv)
{
  std::string str = "Hello, world! n This is new line 2 n and last one 3.";
  std::string regex = ".*2.*n.*3.*";
  std::regex reg(regex, std::regex::extended);
  std::cout << "Input: " << str << std::endl;
  if(std::regex_match(str, reg))
    std::cout << "Match" << std::endl;
  else
    std::cout << "NOT match" << std::endl;
  return 0;
}