2015-11-02 79 views
0

我试图检测无效的输入,其中变量n不应该包含任何符号:;:"'[]*^%$#@!,在regex r定义,在下面的代码:使用正则表达式来检查输入有效性吗?

#include "iostream" 
#include "string" 
#include "sstream" 
#include "regex" 

using namespace std; 

struct Person{ 

    // constructor 
    Person(string n, int a) 
     : name(n), age(a) { 
     if (a <= 0 || a > 150) throw std::out_of_range("Age out of range."); 

     // regex r(";:\"\'[]*^%$#@!"); 
     // regex r("\:|\;|\"|\'|\[|\]|\*|\^|\%|\$|\#|\@|\!"); 
     // regex r("/[\:\;\"\'\[\]\*\^\%\$\#\@\!]/"); 
     // regex r("/[;:\"\'[]*^%$#@!]/"); 

     smatch matches; 
     regex_match(n, matches ,r); 
     if (!matches.empty()) throw std::invalid_argument("Name contains invalid symbols."); 
    } 

    // data members 
    string name; 
    int age; 
}; 

//----------------------------------------------------------------------------------------- 
int main(){ 

    try{ 

    vector<Person> people; 

    string input_termination = "end"; 
    while(true){ 
     cout <<"Type name and age; terminate with \"end\":\n>>"; 

     string line; 
     getline(cin, line); 

     stringstream ss(line); 

     string n; 
     int a; 

     ss >> n >> a; 

     if (n == input_termination) break; 
     else people.emplace_back(Person(n,a)); 
    } 

    cout <<"\nStored people: \n"; 
    for (auto it = people.begin(); it != people.end(); ++it) cout << *it <<'\n'; 

    } catch (exception& e){ 
     cerr << e.what() << endl; 
     getchar(); 
    } catch (...){ 
     cerr <<"Exception!" << endl; 
     getchar(); 
    } 

} 

注释行都是不成功的尝试,其要么导致没有throw 或在下面的错误消息:

regular expression error

如何在上述构造函数中正确定义和使用regex,以便n被检测到,如果它包含任何禁止符号?

注:我已阅读了建议的来源。


1.当一个无效的名称,含有一些符号,用于初始化一个对象。

+0

你必须修复你的模式。你想匹配什么? –

+0

我试图匹配以下模式:'“;:”'[] * ^%$#@!!'',即名称不应包含任何以前的符号。 – Ziezi

+0

您需要转义某些特殊字符使用'\''字符,这种模式'::\\\“\\\'\ [\] \ * \ ^%\ $#@!'应该可以工作。另外,为了将来的参考,有像https://www.debuggex.com/这样的网站,真正有助于处理正则表达式 –

回答

1

的主要问题是,有需要被以与\字符转义正则表达式引擎读取它本身(即*是一个特殊的记号含义匹配0个或更多的某些特殊字符以前的令牌)。这意味着你不仅需要躲避平常' && "人物,有一个你需要用\字符前缀

您可以用比达到你想要什么有类似的图案其他的:

";:\\\"\\\'\[\]\*\^%\$#@!"