使用正则表达式检查输入的有效性
Using regex to check input validity?
我正在尝试检测无效输入,其中变量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
1,要么导致以下错误消息:
regular expression error
如何在上述构造函数中正确定义和使用regex
,以便在n
包含任何禁用符号时检测到它?
注:我已经阅读了建议的来源。
1.当一个包含一些符号的无效名称用于初始化对象时
主要问题是,有些特殊字符需要用字符转义,以便正则表达式引擎将其作为自身读取(即,
*
是一个特殊的令牌,表示与前一个令牌的0个或多个匹配)。这意味着您不仅需要转义常见的' && "
字符,还需要在其他字符前面加上字符
你可以用这样的模式来实现你想要的
";:\"'[]*^%$#@!"
相关文章:
- 在C++程序中输入的文本文件将不起作用,除非文本被复制和粘贴
- 2D数组来自文本输入,中间有空格
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 检查输入是否不是整数或数字
- 正在尝试了解输入验证循环
- 读取文件并输入到矢量中
- C++如何通过用户输入删除列表元素
- 用c++从输入文件中读取另一行
- 读取文件的最后一行并输入到链接列表时出错
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 如何使用用户输入在C++中正确填充2D数组
- C++MySQL C api用户输入行
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 用户定义函数中的指针和输入
- 如何在C++中检查2D数组中负值的输入验证
- 如何从 Python 扩展检查输入变量的有效性
- 使用正则表达式检查输入的有效性
- QLineEdit with QValidator:不管输入的有效性如何,对编辑完成做出反应
- 读取输入数据并检查其有效性的通用宏
- 检查输入有效性