【问题标题】:Can you use Boost.Regex to parse a stream?你可以使用 Boost.Regex 来解析流吗?
【发布时间】:2010-10-02 05:42:22
【问题描述】:

我正在使用 Boost.Regex 来解析字符串中的单词和数字。这是我目前所拥有的:

#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;
}

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

【问题讨论】:

  • 您可以在没有+ 的情况下仅通过"a" "b" 连接字符串吗?哇我从没见过……这是标准吗?
  • 是的,这在 C 和 C++ 中一直是标准的。您可以像这样连接字符串常量,但不能连接 C++ std::strings。

标签: c++ regex boost stream


【解决方案1】:

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

可以通过 Boost.Regex 的“partial match”支持对流的内容进行正则表达式搜索,而无需将其完全加载到内存中。请看页面末尾的示例。

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

      有限状态机需要能够“备份”,以防它现在尝试的操作失败。这对于无法“备份”的输入迭代器来说是不可能的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-09-22
        • 1970-01-01
        • 2011-01-27
        • 1970-01-01
        • 1970-01-01
        • 2011-06-17
        • 2012-09-14
        相关资源
        最近更新 更多