无法使用 regex_search 匹配子字符串

cannot match substring using regex_search

本文关键字:字符串 search regex      更新时间:2023-10-16

为什么会失败?我正在尝试使用 C++STL 中的正则表达式匹配子字符串。 我在这里做错了什么?

海湾合作委员会版本 :: (利纳罗 海湾合作委员会 4.8-2014.04) 4.8.3

#include<regex>
using namespace std;
int main()
{
regex e("auth");
smatch m;
string s="Connected to a:b:c:d completed auth id=3, str=3";
//string s="auth";
bool match = regex_search(s,e);
if( match == true )
printf("matched");
else
printf("no match");
}

根据文档 std::regex_match 只匹配整个字符串。你可能想要 std::regex_search

#include<regex>
using namespace std;
int main()
{
regex e("auth");
smatch m;
string s="Connected to a:b:c:d completed auth id=3, str=3";
//string s="auth";
bool match = regex_search(s,e);
if( match == true )
printf("matched");
else
printf("no match");
}

此外,您应该检查您的实现是否支持std::regex这是C++11中的新功能。例如,GCC编译器仅在4.9.0及更高版本中正确实现<regex>