2009-01-19 37 views
10

我正在玩Boost.Regex來解析字符和數字的字符串。這是我到目前爲止:你可以使用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; 
} 

有沒有辦法讓正則表達式從一個流而不是一個字符串解析?似乎應該可以使用任何迭代器。

+0

你可以用``a「」b「`連接字符串而不用`+`嗎?哇,我從來沒有見過......那是標準嗎? – 2011-01-25 18:17:53

回答

5

Boost.IOStreams有一個regex_filter,允許在流上執行regex_replace的等價操作。然而,看着實現,它似乎「欺騙」,因爲它只是將整個流加載到緩衝區中,然後在該緩衝區上調用Boost.Regex。

通過Boost.Regex的「partial match」支持可以完成對流內容的正則表達式搜索,而無需將其完全加載到內存中。看看頁面末尾的例子。

2

regex_iterator構造函數需要BidirectionalIterators,但std :: istream_iterator只是一個InputIterator,所以看起來你不能用任何標準流類和/或對象(cin,ifstream等)來做到這一點。 )。如果你有一個暴露了雙向迭代器的自定義流,它應該可以工作。

1

有限狀態機需要能夠「備份」,以防現在嘗試失敗。對於不能「備份」的輸入迭代器來說這是不可能的。