多行正则表达式

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

我正在尝试处理包含 IP 地址和子网掩码的文本文件。但是我似乎无法正确使用正则表达式来提取两者:

    std::string testString = "192.168.0.4\r\n255.255.255.0";
    std::regex ipStr("(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])");
    std::smatch sm;
    regex_match (testString, sm, ipStr);
    
    int matches = sm.size();

    for (int i = 0; i <matches; ++i) {
        std::cout  << sm[i] << std::endl;
    }

这不会打印任何内容。我预计

size
是 2。

如果我在 https://regex101.com/ 进行测试,它似乎确实有效。有人看到我做错了什么吗?

c++ regex
1个回答
0
投票

来自 cppreference,https://en.cppreference.com/w/cpp/regex/regex_match

请注意,std::regex_match只能成功将正则表达式与整个字符序列匹配,而std::regex_search将成功匹配子序列。

© www.soinside.com 2019 - 2024. All rights reserved.