linux g++正则表达式不工作

问题描述 投票:0回答:2

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

例如:.C++中的子字符串,在windows c++中也能用,但在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++中却不能用,问题出在哪里?

c++ regex linux g++
2个回答
1
投票

你不需要在':'前加上'\'。所以正确的行是。std::regex re("SerialNumber: (.*)\n"); 这样你的代码就可以在gcc 4.9.1开始的gcc中工作了。https:/wandbox.orgpermlinkuuVCxdtpHAjZTghP


0
投票

<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
© www.soinside.com 2019 - 2024. All rights reserved.