23.9使用正则表达式进行模式匹配
2019-10-07 本文已影响0人
Jianbaozi
#include<iostream>
#include<regex>
#include<string>
#include<cstring>
#include<fstream>
using namespace std;
template<typename T>T from_string(const string& s){
istringstream is{s};
T t;
is>>t;
return t;
}
int main(){
ifstream ifs{"D:\\Codes\\test\\data.txt"};
if(!ifs)
cout<<"Open file error!\n";
cout<<"Open file success!\n";
string line;
int lineno=0;
regex header{R"(^[\w ]+( [\w ]+)*$)"};
regex row{R"(^[\w ]+( \d+)( \d+)( \d+)$)"};
if(getline(ifs,line)){
smatch matches;
if(!regex_match(line,matches,header))
cout<<"No header!\n";
cout<<matches[0]<<'\n';
}
int boys=0;
int girls=0;
while(getline(ifs,line)){
++lineno;
smatch matches;
if(!regex_match(line,matches,row))
cout<<"bad line!\n";
int curr_boy=from_string<int>(matches[1]);
int curr_girl=from_string<int>(matches[2]);
int curr_total=from_string<int>(matches[3]);
cout<<"line "<<lineno<<":\t"<<curr_boy<<" "<<curr_girl<<" "<<curr_total<<'\n';
if(curr_total!=curr_boy+curr_girl)
cout<<" bad row sum at"<<lineno<<'\n';
string s=matches[0];
if(s.substr(0,12)=="Alle klasser"){
cout<<"Total line find!\n";
if(curr_boy!=boys) cout<<"boys don't add up!\n";
if(curr_girl!=girls) cout<<"girls don't add up!\n";
if(!(ifs>>ws).eof()) cout<<"characters after total line\n";
return 0;
}
boys+=curr_boy;
girls+=curr_girl;
}
cout<<"didn't find total line!\n";
system("pause");
return -1;
}
测试文件
KLASSE ANTAL DRENGE ANTAL PIGER ELEVER IALT
0A 12 11 23
1A 7 8 15
1B 4 11 15
2A 10 13 99999s
3A 10 12 22
4A 7 7 14
Alle klasser 50 62 112
blah..blah
输出结果
D:\Codes\test>a.exe
Open file success!
KLASSE ANTAL DRENGE ANTAL PIGER ELEVER IALT
line 1: 12 11 22
bad row sum at1
line 2: 7 8 15
line 3: 4 11 15
line 4: 10 13 23
line 5: 10 12 22
line 6: 7 7 14
line 7: 50 62 112
Total line find!
characters after total line
D:\Codes\test>a.exe
Open file success!
KLASSE ANTAL DRENGE ANTAL PIGER ELEVER IALT
line 1: 12 11 23
line 2: 7 8 15
line 3: 4 11 15
line 4: 10 13 99999
bad row sum at4
line 5: 10 12 22
line 6: 7 7 14
line 7: 50 62 112
Total line find!
characters after total line