首页 > 解决方案 > 正则表达式匹配整个字符串

问题描述

我正在尝试使用正则表达式来匹配整个字符串,但我得到了一些奇怪的结果。

这个想法是匹配一个 IP 地址字符串,或者一个部分类型的 IP 地址字符串。

即被23.44允许,因为它是部分输入的

244.655.不允许,因为 655 太高了。

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

int main()
{
    std::string str1 = "23.4f";
    std::string str2 = "234.233.12";
    std::string str3 = "fdfdf";
    std::string str4 = "f233.21.3";

    std::regex reg("^(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])(\.((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])(\.((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9])(\.((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9][0-9]|[0-9]))?)?)?)?)?)?$",std::regex::ECMAScript|std::regex::optimize);

    if(std::regex_match(str1,reg))
        std::cout << "string 1 matches" << std::endl;

    if(std::regex_match(str2,reg))
        std::cout << "string 2 matches" << std::endl;

    if(std::regex_match(str3,reg))
        std::cout << "string 3 matches" << std::endl;

    if(std::regex_match(str4,reg))
        std::cout << "string 4 matches" << std::endl;

    return 0;
}

输出是

string 1 matches
string 2 matches

我认为它在第一部分有匹配,str1但我认为首先regex_match必须匹配整个字符串,然后在正则表达式模式中添加字符串边界将确保整个匹配。

我究竟做错了什么?

标签: c++regex

解决方案


推荐阅读