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/这样的网站,真正有助于处理正则表达式 –