代码之家  ›  专栏  ›  技术社区  ›  Ferruccio

可以使用Boost.Regex解析流吗?

  •  10
  • Ferruccio  · 技术社区  · 17 年前

    #include <iostream>
    #include <string>
    #include <boost/foreach.hpp>
    #include <boost/regex.hpp>
    #include <boost/range.hpp>
    
    using namespace std;
    using namespace boost;
    
    int main()
    {
        regex re
        (
            "("
                "([a-z]+)|"
                "(-?[0-9]+(\\.[0-9]+)?)"
            ")"
        );
    
        string s = "here is a\t list of Words. and some 1239.32 numbers to 3323 parse.";
        sregex_iterator m1(s.begin(), s.end(), re), m2;
    
        BOOST_FOREACH (const match_results<string::const_iterator>& what, make_iterator_range(m1, m2)) {
            cout << ":" << what[1].str() << ":" << what.position(1) << ":" << what.length(1) << endl;
        }
    
        return 0;
    }
    

    有没有办法告诉正则表达式从流而不是字符串进行解析?似乎应该可以使用任何迭代器。

    3 回复  |  直到 17 年前
        1
  •  5
  •   jan-glx charlie    11 年前

    Boost.IOStreams有一个 regex_filter 允许在流上执行相当于regex_替换的操作。然而,从实现的角度来看,它似乎是“欺骗”的,因为它只是将整个流加载到一个缓冲区中,然后在该缓冲区上调用Boost.Regex。

    对流的内容进行正则表达式搜索而不必将其完全加载到内存中,可以使用“ partial match “支持Boost.Regex。请看本页末尾的示例。

        2
  •  2
  •   Harper Shelby damiankolasa    17 年前

    regex_迭代器构造函数需要双向迭代器,但std::istream_迭代器只是一个输入迭代器,因此您似乎无法对任何标准流类和/或对象(cin、ifstream等)执行此操作。如果您有一个公开双向迭代器的自定义流,它应该可以工作。

        3
  •  1
  •   Puppy    14 年前