2015-11-02 43 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個或更多的某些特殊字符以前的令牌)。這意味着你不僅需要躲避平常' && "人物,有一個你需要用\字符前綴

您可以用比達到你想要什麼有類似的圖案其他的:

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