c++ - 正则表达式匹配整个字符串
问题描述
我正在尝试使用正则表达式来匹配整个字符串,但我得到了一些奇怪的结果。
这个想法是匹配一个 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
必须匹配整个字符串,然后在正则表达式模式中添加字符串边界将确保整个匹配。
我究竟做错了什么?
解决方案
推荐阅读
- laravel - .env 文件中系统定义的环境变量
- reactjs - 使用 Mobx 时如何解决 `reaction is not defined`?
- javascript - 在 vue 中重新加载/刷新时保留表单中的填充字段
- azure - 新创建的 VM 未出现在 VM 列表中
- ios - 反应原生“'AIRMapCoordinate.h'文件未找到”错误
- javascript - 多个动画在css中一次旋转调用一个元素的切换onclick(慢速旋转,中等旋转,快速旋转)?
- c++ - 如何在paintEvent() 之外绘制?Qt, C++
- bash - If/Else 语句检查是否提供了参数
- mysql - MySQL Node JS DELETE 无效 - 0 行受影响
- hive - 在插入覆盖中禁用 Hive 压缩的选项