C ++正则表达式匹配,不匹配

时间:2016-08-21 03:12:14

标签: regex c++11

所以我在std :: string中有以下文本:

2: enp1s0: <NO-CARRIER,BROADCAST,MULTICAST,UP> mtu 1500 qdisc fq_codel state DOWN mode DEFAULT group default qlen 1000\    link/ether 68:f7:28:4e:7b:ac brd ff:ff:ff:ff:ff:ff

我试图提取&#39; enp1s0&#39;和&#39; 68:f7:28:4e:7b:ac&#39;使用以下正则表达式:

\d{1}:\s+(\w+).*link\/ether\s{1}([a-z0-9:]+)

适用于在线正则表达式测试程序,但此C ++代码未检测到匹配项:

std::regex interface_address("^\\d{1}:\\s+(\\w+).*link\\/ether\\s{1}([a-z0-9:]+)");
std::smatch pieces;
if (std::regex_match(line, pieces, interface_address)) {
    std::string name = "";
    std::string address = "";
    for (size_t i = 0; i < pieces.size(); ++i) {
        auto submatch = pieces[i];
        if (i == 0) {
            name = submatch.str();
        } else if (i == 1) {
            address = submatch.str();
        }
    }
    std::cout << name << address << std::endl;
}

我哪里错了?

1 个答案:

答案 0 :(得分:1)

当字符串与模式完全匹配时,regex_match失败。请注意,字符串的brd ff:ff:ff:ff:ff:ff部分未匹配。那么,您需要做的就是在模式中添加。*:

^\\d{1}:\\s+(\\w+).*?link\\/ether\\s{1}([a-z0-9:]+).*

此外,对于该示例,循环不是必需的。您可以使用:

if (std::regex_match(line, pieces, interface_address)) {
    std::string name = pieces[1];
    std::string address = pieces[2];
    std::cout << name << address << std::endl;
}