我正在研究c 11中的正则表达式,这个正则表达式搜索返回false.有谁知道我在做错了什么? .我知道.*代表除换行符之外的任意数量的字符.
所以我期待regex_match()返回true并将输出“找到”.
然而,输出结果是“未找到”.
#include<regex>
#include<iostream>
using namespace std;
int main()
{
bool found = regex_match("<html>",regex("h.*l"));// works for "<.*>"
cout<<(found?"found":"not found");
return 0;
}
您需要使用regex_search而不是regex_match:
bool found = regex_search("<html>",regex("h.*l"));
见IDEONE demo
简单来说,regex_search将在给定字符串中的任何位置搜索子字符串.如果整个输入字符串匹配,则regex_match将仅返回true(与Java中的匹配行为相同).
regex_match文件说:
Returns whether the target sequence matches the regular expression
rgx.
The entire target sequence must match the regular expression for this function >to return true (i.e.,without any additional characters before or after the >match). For a function that returns true when the match is only part of the >sequence,seeregex_search.
regex_search是不同的:
Returns whether some sub-sequence in the target sequence (the subject) matches the regular expression
rgx(the pattern).