2012-12-03 9 views
5
#include <algorithm> 
#include <iostream> 
#include <string> 
#include <vector> 

#define BOOST_SPIRIT_UNICODE // We'll use unicode (UTF8) all throughout 

#include <boost/spirit/include/qi.hpp> 
#include <boost/spirit/include/qi_parse.hpp> 
#include <boost/spirit/include/support_standard_wide.hpp> 

void parse_simple_string() 
{ 
    namespace qi = boost::spirit::qi;  
    namespace encoding = boost::spirit::unicode; 
    //namespace stw = boost::spirit::standard_wide; 

    typedef std::wstring::const_iterator iterator_type; 

    std::vector<std::wstring> result; 
    std::wstring const input = LR"(12,3","ab,cd","G,G\"GG","kkk","10,\"0","99987","PPP","你好)"; 

    qi::rule<iterator_type, std::wstring()> key = +(qi::unicode::char_ - qi::lit(L"\",\"")); 
    qi::phrase_parse(input.begin(), input.end(), 
        key % qi::lit(L"\",\""), 
        encoding::space, 
        result); 

    //std::copy(result.rbegin(), result.rend(), std::ostream_iterator<std::wstring, wchar_t> (std::wcout, L"\n")); 
    for(auto const &data : result) std::wcout<<data<<std::endl; 
} 

は、私がこの記事How to use Boost Spirit to parse Chinese(unicode utf-16)? を研究し、期待どおりの結果がboost :: spiritを使ってUTF-8を解析する方法は?

12,3 AB、CD G、Gでなければなりませんガイドに従いますが、言葉 "你好"

を解析するために失敗します\ "GG KKK 10、\" 0 PPP 你好

が、実際の結果はです12,3 AB、CD G、G \ "GG KKK 10、\" 0 PPP

は中国語の単語 "你好"

OSが私の、win7の64-ビットでの解析に失敗しましたUTF-8として単語を保存します

+1

私は混乱しています。あなたは... UTF8を使用していますか?それではなぜwstring? (UTF8はエンコーディングのシングル/ダブル/トリプルバイトシーケンス、右)です。私は説明する資格があるとは思わないが、これは私の知覚の不一致である – sehe

+0

1-4バイト。しかし、はい、それはかなり明るい不一致です。 'char8_t'が導入されるまで、' char'は大部分のUTF-8タイプです。 – Puppy

+5

誰もが言った。 'wstring'はUTF-8を使うときに間違っています。 Windowsで正しくエンコードされたUTF-8リテラル、*特に*が必要な場合は、最も安全な方法はC++ 11リテラルの 'u8 'blah"(Visual Studioにはまだありません)か、 "你好"の代わりに "\ xE4 \ xBD \ xA0 \ xE5 \ xA5 \ xBD"を直接エンコーディングしてください。 –

答えて

8

入力時にUTF-8を使用している場合は、Unicode IteratorsBoost.Regexから試してみてください。

例えば、利用ブースト:: u8_to_u32_iterator:UTF8文字の配下のシーケンスを作る

A双方向イテレータアダプタはUTF32文字の(読み取り専用)シーケンスのように見えます。

live demo

#include <boost/regex/pending/unicode_iterator.hpp> 
#include <boost/spirit/include/qi.hpp> 
#include <boost/range.hpp> 
#include <iterator> 
#include <iostream> 
#include <ostream> 
#include <cstdint> 
#include <vector> 

int main() 
{ 
    using namespace boost; 
    using namespace spirit::qi; 
    using namespace std; 

    auto &&utf8_text=u8"你好,世界!"; 
    u8_to_u32_iterator<const char*> 
     tbegin(begin(utf8_text)), tend(end(utf8_text)); 

    vector<uint32_t> result; 
    parse(tbegin, tend, *standard_wide::char_, result); 
    for(auto &&code_point : result) 
     cout << "&#" << code_point << ";"; 
    cout << endl; 
} 

出力は次のとおりです。

&#20320;&#22909;&#65292;&#19990;&#30028;&#65281;&#0; 
+0

+1良い仕事の先生 – sehe

関連する問題