此处的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;
}
答案 0 :(得分:2)
首先,you don't parse HTML with regex。
但是,如果你这样做,你确实在调用中有参数不匹配
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"));
关于最长匹配的问题 更新 - 您必须使用非贪婪的匹配限定符,例如.*?