代码之家  ›  专栏  ›  技术社区  ›  hromer

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

  •  -1
  • hromer  · 技术社区  · 7 年前

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

    3月25日19:17:55 127.0.0.1用户:[pool-15-thread-17]INTOUCH;0;信息;SOFTLOADSERVICE;安装已启动

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

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

    不幸的是,我似乎找不到任何匹配项。有什么建议吗?

    2 回复  |  直到 7 年前
        1
  •  1
  •   BJovke    7 年前

    如果正则表达式与希望它匹配的字符串不匹配,则正则表达式是错误的。我已更正了您的正则表达式:

    (\\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/

        2
  •  0
  •   einpoklum    7 年前

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

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

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