c ++ regex:如何使用子匹配

时间:2016-10-09 17:45:58

标签: c++ regex

此代码将输出192.168.1.105,但我希望它能找到ip的每个数字部分。输出将是

192
168
1
105

由于ip_result只有1个子匹配(192.168.1.1),我如何为每个数字部分获得4个子匹配?

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

2 个答案:

答案 0 :(得分:1)

我重写了ip_reg以使用子模式和print_results来使用迭代器

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

答案 1 :(得分:0)

如果您将std::regex_match替换为std::regex_search,请将其循环并始终删除匹配项,即可访问所有子匹配项。此外,您需要将表达式更改为仅一个数字组:

 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" ...
    }
}

输出:

192
168
1
105