【问题标题】:Multilines regex in C++C ++中的多行正则表达式
【发布时间】:2017-09-07 23:54:48
【问题描述】:

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

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

【问题讨论】:

  • 抱歉,代码并没有很好地说明您想要实现的目标。请解释要求,提供示例文本和预期输出。
  • @WiktorStribiżew,我尝试打开一个文本文件,在字符串中读取并存储字符,并在字符串上使用正则表达式来查找我的正则表达式中的数字,但我无法解析多行。那是我的问题。
  • @WiktorStribiżew,我将尝试发布一个简单的示例。

标签: c++ regex multilinestring


【解决方案1】:

在构造正则表达式对象时可以指定一些标志,请参阅 文档http://en.cppreference.com/w/cpp/regex/basic_regex 了解详情。

带有 regex::extended 标志的简短工作示例,其中在搜索中指定换行符“\n”如下:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-29
    相关资源
    最近更新 更多