gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 10:24:55 27 4
gpt4 key购买 nike

实际上,我尝试在多行字符串中查找正则表达式,但是我认为在换行之后查找下一个正则表达式的方式是错误的(等于'\ 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);
}

最佳答案

构造正则表达式对象时可以指定一些标志,请参见
有关详细信息,请参见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;
}

关于c++ - C++中的多行正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43365506/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com