2016-04-05 11 views
0

C++でboost regexを使ってテキストファイルを解析しています。私はファイルから '\'文字を探しています。このファイルには、Unicodeの「\ u」文字も含まれています。だから、 '\'と '\ u'文字を分ける方法はありますか?私はそれが代わりに私が欲しいのC++でboost regexを使ってエスケープエレメント ''とUnicode文字 ' u'をパースする方法

"ID": "\u01FE234DA - this is id ", 
(\) found 
"ID": "\u01FE234DA - this is id ", 
unicode found 
"speed": "96\/78", 
(\) found 
"avg": "\u01FE234DA avg\83" 
(\) found 
"avg": "\u01FE234DA avg\83" 
unicode found 

次のプリントのコード上で使用する場合 後、私は以下の

"ID": "\u01FE234DA - this is id ", 
"speed": "96\/78", 
"avg": "\u01FE234DA avg\83" 

を解析していますのtest.txtの内容は、今私の試み

#include <boost/regex.hpp> 
#include <string> 
#include <iostream> 
#include <fstream> 

using namespace std; 
const int BUFSIZE = 500; 

int main(int argc, char** argv) { 

    if (argc < 2) { 
     cout << "Pass the input file" << endl; 
     exit(0); 
    } 

    boost::regex re("\\\\+"); 
    string file(argv[1]); 
    char buf[BUFSIZE]; 

    boost::regex uni("\\\\u+"); 


    ifstream in(file.c_str()); 
    while (!in.eof()) 
    { 
     in.getline(buf, BUFSIZE-1); 
     if (boost::regex_search(buf, re)) 
     { 
      cout << buf << endl; 
      cout << "(\) found" << endl; 
      if (boost::regex_search(buf, uni)) { 
       cout << buf << endl; 
       cout << "unicode found" << endl; 

      } 

     } 

    } 
} 

されています続く

"ID": "\u01FE234DA - this is id ", 
unicode found 
"speed": "96\/78", 
(\) found 
"avg": "\u01FE234DA avg\83" 
(\) and unicode found 

私はコードが '\'と '\ u'を区別することができないと思いますが、どこを変更するのかは分かりません。

+0

あなたの現在のコードは、コメントアウトされたステートメントのために表示する出力を生成しません**。また、両方のチェックを実行すると何が問題になりますか? (これはとにかく欠陥のある方法ですが、正規表現を使用せず、一度に1つのバックスラッシュを調べて、最初から最後まで調べてください)。 – usr2564301

+0

正規表現を使用しましょう。 「ID」フィールドが2回表示されます。つまり、 "ID"はユニコードと見なされますが、(\)が見つかりました – kkard

+0

私はコードがうまくいくと思います。 – kkard

答えて

1

あなたの最初の正規表現で[u]を使って、u以外の文字にマッチさせてみてください。

boost::regex re("\\\\[^u]"); // matches \ not followed by u 
boost::regex uni("\\\\u"); // matches \u 

おそらく1つの正規表現を使用することをお勧めします。

m = boost::regex_search(buf, uni) 
if (m && m[1] === "u") { // pseudo-code 
    // unicode 
} 
else { 
    // not unicode 
} 

それは、パターンマッチングのための正規表現を使用することをお勧めします:部分一致m[1]は 'U' の場合

boost:regex re("\\\\(u)?"); // matches \ with or without u 

次にチェック。それらはもっと複雑に思えますが、一度に文字を1文字ずつ繰り返すよりも、使い慣れたほうが実際には維持しやすくなります。

関連する問題