c++ - 使用 boost 在文件中查找正则表达式

标签 c++ regex file 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));

错误如下:

Could not find a match for 'bind2nd<_Fn2,_Ty>(bool (*) (BidiIterator,BidiIterator,match_results &,const basic_regex &,unsigned long))'

Could not find a match for 'find(istream_iterator,int>,istream_iterator,int>,undefined,regex)'

你能帮我正确地做一下吗?谢谢。

最佳答案

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

下一个问题是 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() 的另一个原因。

关于c++ - 使用 boost 在文件中查找正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12772912/

相关文章:

c++ - 你能在 C++ 中保护嵌套类吗?

regex - 将大量字符串与固定数量的正则表达式模式进行匹配的高效算法

java - Android Java 正则表达式替换重复模式如图所示

c - 如何在C中获取源文件(我要复制的文件)和复制文件的信息

linux - 同一个文件的两个文件描述符

c++ - 使用默认复制构造函数时出错 : "deleted function"

c++ - Qt UI 测试:无法执行 QTest::keyPress

c++ - 如何通过 Mersenne Twister 生成不重复的随机变量

python - Linux 发行版名称解析

python - python中返回文件扩展名的函数