23.8.7正则表达式错误

2019-10-07  本文已影响0人  Jianbaozi
#include<regex>
#include<iostream>
#include<sstream>
#include<fstream>
#include<string>
using namespace std;
int main() {
    cout << "Input pattern: ";
    string pat;
    regex pattern;
    getline(cin,pat);
    try{
        pattern=pat;
        cout<<"Pattern is: "<<pat<<'\n';
    }catch(...){  //bad_expression 编译报错 
                      //gcc version 5.1.0 (x86_64-posix-seh-rev0, Built by MinGW-W64 project)
        cout<<pat<<" is not a valid regular expression.";
        exit(1);
    }
    cout<<"Enter lines:\n";
    int lineno=0;
    for(string line;getline(cin,line);){
        ++lineno;
        smatch matches;
        if(regex_search(line,matches,pattern)){
            cout<<"line "<<lineno<<": "<<line<<'\n';
            for(int i=0;i<matches.size();++i){
                cout<<"\tmatches["<<i<<"]"<<matches[i]<<'\n';
            }
        }
        else
            cout<<"line "<<lineno<<": "<<line<<'\n'<<"didn't match!"<<endl;        
        }
    system("pause");
    return 0;
}

编译提示:

D:/mingw64/x86_64-w64-mingw32/include/c++/bits/c++0x_warning.h:32:2: error: #error This file requires compiler and library support for the ISO C++ 2011 standard. This support is currently experimental, and must be enabled with the -std=c++11 or -std=gnu++11 compiler options.
 #error This file requires compiler and library support for the \
  ^
test.cpp: In function 'int main()':
test.cpp:10:5: error: 'regex' was not declared in this scope
     regex pattern;
     ^
test.cpp:11:17: error: 'pattern' was not declared in this scope
     getline(cin,pattern);
                 ^
test.cpp:15:12: error: 'bad_expression' does not name a type
     }catch(bad_expression){
            ^

测试:

PS D:\Codes\test> g++ test.cpp -std=c++11   
PS D:\Codes\test> ./a.exe
Input pattern: \w{3}(\d{3})
Pattern is: \w{3}(\d{3})
Enter lines:
abc123
line 1: abc123
        matches[0]abc123
        matches[1]123   
456def
line 2: 456def
didn't match! 
aabbcc789
line 3: aabbcc789       
        matches[0]bcc789
        matches[1]789   
上一篇 下一篇

猜你喜欢

热点阅读