使用boost在文件中查找regex
Find regex in file with boost
我想做这样的事情:
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()
的另一个原因。
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 在C++中查找文件
- 模板元程序查找相似的连续类型名称
- 在UNIX系统中使用DIR查找文件的字节大小
- 查找最接近的大于当前数字的数字的索引
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 查找后更改类变量
- 使用正则表达式regex_search在字符串中查找字符串
- 使用gcc从静态链接的文件中查找可选符号
- 在C++中查找范围的长度
- 此模式的C++RegEx
- 算法问题:查找从堆栈中弹出的所有序列
- C++:如何用split查找单词?Regex
- 使用boost在文件中查找regex
- 在Qt中使用regex查找两个标签之间的字符串
- 如何使用 std::regex 查找字符串中的下一个匹配项
- 使用 std::regex 查找函数的内容
- std::regex查找字符串中括号内的单词,然后替换它(和括号)
- C++在不带Regex的字符串中查找单词
- Regex查找复杂参数