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.當一個無效的名稱,含有一些符號,用於初始化一個對象。
你必須修復你的模式。你想匹配什麼? –
我試圖匹配以下模式:'「;:」'[] * ^%$#@!!'',即名稱不應包含任何以前的符號。 – Ziezi
您需要轉義某些特殊字符使用'\''字符,這種模式'::\\\「\\\'\ [\] \ * \ ^%\ $#@!'應該可以工作。另外,爲了將來的參考,有像https://www.debuggex.com/這樣的網站,真正有助於處理正則表達式 –