linux g++ 正则表达式不起作用

linux g++ regular expressions not working

我试图在 linux g++ 上使用正则表达式查找子字符串。

例如:

    std::string logline = "Apr 19 00:55:32 localhost kernel: usb 2-2.1: SerialNumber: ABCDEFGHIJKLMNOP\n";

    std::string sn = "";
    std::regex re("SerialNumber\: (.*)\n");
    std::smatch match;
    if (std::regex_search(logline, match, re) && match.size() > 1) {
        sn = match.str(1);
    }
    else
    {
        sn = std::string("");
    }

它也适用于 windows c++。 但是 linux g++ 不起作用。 有什么问题吗?

<regex> 已在 GCC 4.9.0 中实现和发布,因此请检查您的 gcc 版本并查看以下示例:

#include <regex> //header  file for regex
#include <iostream>

int main(int argc, const char * argv[]){
    std::regex r("ab|bc|cd");
    std::cerr << "ab|bc|cd" << " matches ab? " << std::regex_match("sab", r) << std::endl;
    return 0;
}

输出:

ab|bc|cd matches ab? 1

您不需要在“:”之前使用“\”。所以正确的行是: std::regex re("SerialNumber: (.*)\n"); 通过此更改,您的代码可以从 gcc 4.9.1 开始使用 gcc。 https://wandbox.org/permlink/uuVCxdtpHAjZTghP