[英]regex_search only selecting biggest substring that matches. Also type mismatch in regex_search
regex_search此处仅选择该程序中最长的子字符串,因为输出是整个字符串数据。 这是默认行为吗?
另外,如果我先传递字符串而不先声明为字符串,就这样
regex_search("<html><body>some data</body></html",m,samepattern)
它引发类型不匹配的错误。
此外,如果我仅在没有附加第二个参数的情况下使用
regex_search("some string",pattern);
有用。
整个代码如下所示
#include<string>
#include<regex>
#include<iostream>
#include<iomanip>
using namespace std;
int main()
{
smatch m;
string data{"<html><body>some data</body></html"};
bool found = regex_search(data,m,regex("<.*>.*</.*>"));
//If regex_seacrh("<html><body>some data</body></html",same as above)
//it throws type mismatch error for this string in regex header
cout<<(found?m.str():"not found");
return 0;
}
首先, 您不使用regex解析HTML 。
但是,如果这样做,您确实在调用中存在参数不匹配的情况
smatch m;
bool found = regex_search("some data", m, regex("some regex"));
相应的regex_search()
重载必须为:
template <class charT, class Allocator, class traits>
bool regex_search(const charT* str,
match_results<const charT*, Allocator>& m,
const basic_regex<charT, traits>& e,
regex_constants::match_flag_type flags =
regex_constants::match_default);
但是m
是smatch
类型,它是match_results<std::string::const_iterator>
。
您应该使用cmatch
而不是smatch
:
cmatch m;
bool found = regex_search("some data", m, regex("some regex"));
更新有关最长匹配的问题-您必须使用非贪婪匹配限定符,例如.*?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.