Brady Dean
Brady Dean

Reputation: 3573

c++ regex: how to use sub-matches

This code will output 192.168.1.105 but I want it to find each number-part of the ip. The output would be

192
168
1
105

Since the ip_result only has 1 sub-match (192.168.1.1), how would I get 4 submatches for each number-part?

#include <iostream>
#include <regex>
#include <string>

std::regex ip_reg("\\d{1,3}."
                  "\\d{1,3}."
                  "\\d{1,3}."
                  "\\d{1,3}");

void print_results(const std::string& ip) {
    std::smatch ip_result;
    if (std::regex_match(ip, ip_result, ip_reg))
        for (auto pattern : ip_result)
            std::cout << pattern << std::endl;
    else
        std::cout << "No match!" << std::endl;
}

int main() {
    const std::string ip_str("192.168.1.105");
    ip::print_results(ip_str);
}

Upvotes: 0

Views: 5217

Answers (2)

Brady Dean
Brady Dean

Reputation: 3573

I rewrote ip_reg to use sub-patterns and print_results to use iterators

std::regex ip_reg("(\\d{1,3})\\."
                  "(\\d{1,3})\\."
                  "(\\d{1,3})\\."
                  "(\\d{1,3})");

void print_results(const std::string& ip) {
    std::smatch ip_result;
    if (std::regex_match(ip, ip_result, ip_reg)) {
        std::smatch::iterator ip_it = ip_result.begin();
        for (std::advance(ip_it, 1);
             ip_it != ip_result.end();
             advance(ip_it, 1))
            std::cout << *ip_it << std::endl;
    } else
        std::cout << "No match!" << std::endl;
}

Upvotes: 2

Stack Danny
Stack Danny

Reputation: 8126

If you replace std::regex_match with std::regex_search, loop that and always remove the match, you can access all the submatches. Also, you need to change the expression to only one group of digits:

 std::regex ip_reg{ "\\d{1,3}" };

void print_results(const std::string& ip_str) {
    std::string ip = ip_str; //make a copy!
    std::smatch ip_result;

    while (std::regex_search(ip, ip_result, ip_reg)){ //loop

        std::cout << ip_result[0] << std::endl;

        ip = ip_result.suffix(); //remove "192", then "168" ...
    }
}

output:

192
168
1
105

Upvotes: 0

Related Questions