使用boost在文件中查找regex

Find regex in file with boost

本文关键字:查找 regex 文件 boost 使用      更新时间:2023-10-16

我想做这样的事情:

boost::regex re("tryme");
ifstream iss;
iss.open("file.txt");
istream_iterator<string> eos;     
istream_iterator<string> iit (iss);
find(iit,eos,bind2nd(boost::regex_match),re));

错误如下:

找不到'bind2nd<的匹配项_Fn2,_Ty>(bool(*)(BidiIterator、BidiItator、match_results&、const basic_regx&,无符号长))'

找不到"find(istream_iterator,int>,istream_iterator,int>,undefined,regex)"的匹配项

你能帮我正确地做吗?谢谢

第一个问题是std::find()试图匹配值,即需要用std::find_if()替换std::find()。这很简单。

下一个问题是boost::regex_match不是一个函数,而是一个函数族。std::bind2nd()不知道你想与这个家庭的哪个成员匹配。此外,您显然想要使用的函数重载需要三个而不是两个参数:默认为boost::match_flag_type类型的最后一个参数。我让它与std::bind()一起使用这个:

std::bind(static_cast<bool (*)(std::string const&,
boost::regex const&,
boost::match_flag_type)>(&boost::regex_match),
std::placeholders::_1, re);

如果你真的想使用std::bind2nd(),那么创建一个简单的转发功能可能是最简单的:

bool my_regex_match(std::string s, boost::regex const& r) {
return boost::regex_match(s, r);
}
void f() {
boost::regex re("tryme");
std::ifstream iss(file.txt);
std::find_if(std::istream_iterator<std::string>(iss),
std::istream_iterator<std::string>(),
std::bind2nd(std::ptr_fun(&my_regex_match), re));
}

std::bind2nd()模板不能真正使用原始函数指针。这就是为什么需要使用std::ptr_fun()。通常,当需要使用任何一个称为*_fun()的标准函数时,乐趣实际上就停止了:这些函数无法处理通过引用获取参数的函数。因此,my_regex_match()按值取其std::string参数:否则,std::bind2nd()将尝试创建一个函数对象,将对引用的引用作为参数。这也是您可能想要使用std::bind()boost::bind()的另一个原因。