我的 Boost 正则表达式与任何内容都不匹配

My Boost regular expression is not matching anything

本文关键字:不匹配 任何内 Boost 正则表达式 我的      更新时间:2023-10-16

>我正在尝试匹配如下所示的字符串:

3 月 25 日 19:17:55 127.0.0.1 用户:[池-15-线程-17]INTOUCH;0;信息;软加载服务;安装已开始

使用正则表达式。这是我定义正则表达式的代码:

#include <boost/regex.hpp>
#include <boost/date_time/posix_time/posix_time.hpp>
#include <tuple>
#include <string>
const std::string softload_startup = "(\w{3}) (\d{1,2}) (\d{2}): 
(\d{2}):(\d{2})*SOFTLOADSERVICE;Install started\s"; //NOLINT
const boost::regex softload_start(softload_startup);
class InTouchSoftload {
 public:
   explicit InTouchSoftload(std::string filename);
 private:
    std::string _log_name;
    std::tuple<unsigned int, std::string> software_update_start;
};

我在这里称呼它:

 int main() {
        fin.open(input_file);
        if (fin.fail()) {
            std::cerr << "Failed to open " << input_file << std::endl;
            exit(1);
        }
        while (std::getline(fin, line)) {
                line_no++;
                if (regex_match(line, softload_start)) {
                    std::cout << line << std::endl;
                }
            }
        return 0;
    }

不幸的是,我似乎无法获得任何匹配。有什么建议吗?

如果你的正则表达式与你想要它匹配的字符串不匹配,那么你的正则表达式是错误的。我已经更正了您的正则表达式:

(\w{3}) (\d{1,2}) (\d{2}):(\d{2}):(\d{2}).*SOFTLOADSERVICE;Install started\s*

您可以在此处测试正则表达式和您自己:

https://regex101.com/

https://www.regextester.com/

https://regexr.com/

虽然您没有提供完整的示例,但您最近的编辑表明您失败了,因为您正在尝试匹配单个行 - std::getline()的结果,而您的模式涉及两条线。

如果确实如此,您可能应该执行以下操作之一:

    匹配
  • 连续行对(即在每次迭代时尝试匹配上一条+当前行(
  • 将正则表达式拆分为 2 个正则表达式,每行一个。现在,每当一行与第一个正则表达式匹配时,请尝试将下一行与第二行匹配;否则,请尝试将其与第一个匹配。
  • ^添加到正则表达式的开头,$添加到末尾(以便它在行边界上匹配,并将正则表达式与整个输入流匹配,而不是逐行匹配。