1. 程式人生 > 實用技巧 >用正則表示式驗證表格的格式

用正則表示式驗證表格的格式

/*--------------------------------------------------------------
    用正則表示式驗證一個表格的格式。
    如果表格格式合乎要求,程式會輸出 "all is well" 到 cout;
    否則會將錯誤訊息輸出到 cerr。
    一個表格由若干行組成,每行包含四個由製表符分隔的欄位。
    例如:
    Class    Boys    Girls    Total 
    1a       12      15       27
    1b       16      14       30
    Total    28      29       57
  --------------------------------------------------------------
*/ #include <iostream> #include <fstream> #include <regex> #include <string> using namespace std; int main() { ifstream in("table.txt"); //輸入檔案 if(!in) cerr << "no file\n"; string line; //輸入緩衝區 int lineno = 0; regex header {R
"(^[\w]+(\t[\w]+)*$)"}; //製表符間隔的單詞 regex row {R"(^([\w]+)(\t\d+)(\t\d+)(\t\d+)$)"}; //一個標籤後接製表符分隔的三個數值 if(getline(in,line)){ //檢查並丟棄標題行 smatch matches; if(!regex_match(line,matches,header)) cerr << "no header\n"; } int
boys = 0;      //數值總計 int girls = 0; while(getline(in,line)){ ++lineno; smatch matches; if(!regex_match(line,matches,row)) cerr << "bad line: " << lineno << '\n'; int curr_boy = stoi(matches[2]); int curr_girl = stoi(matches[3]); int curr_total = stoi(matches[4]); if(curr_boy+curr_girl!=curr_total) cerr << "bad row sum\n"; if(matches[1]=="total"){ //最後一行 if(curr_boy!=boys) cerr << "boys do not add up\n"; if(curr_girl!=girls) cerr << "girls do not add up\n"; cout << "all is well\n"; return 0; } boys+=curr_boy; girls+=curr_girl; } cerr << "didn't find total line\n"; return 1; }