0

So I have the following text in a 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

and I am trying to extract the 'enp1s0' and '68:f7:28:4e:7b:ac' using the following regex:

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

which works in an online regex tester, but this C++ code does not detect a match:

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

where am i going wrong?

4
  • FYI, there's never any reason for {1} in a regexp. That's the default for any pattern. Commented Aug 21, 2016 at 3:13
  • What's your compiler? Not all compilers support regex well Commented Aug 21, 2016 at 3:14
  • Note that the name should be in pieces[1] and address is in pieces[2]. pieces[0] is the match for the entire regexp. Commented Aug 21, 2016 at 3:32
  • @for_stack: clang++ version 3.8.1 Commented Aug 21, 2016 at 3:49

1 Answer 1

1

The regex_match fails when the string doesnt match EXACTLY the pattern. Note that the brd ff:ff:ff:ff:ff:ff part of the string isnt being matched. All you need to do, then, is to append a .* to the pattern:

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

Also, for that example, the loop isnt necessary. You can use:

if (std::regex_match(line, pieces, interface_address)) {
    std::string name = pieces[1];
    std::string address = pieces[2];
    std::cout << name << address << std::endl;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.