gpt4 book ai didi

c++ - 使用正则表达式检查输入有效性?

转载 作者:行者123 更新时间:2023-11-28 05:59:51 24 4
gpt4 key购买 nike

我正在尝试检测无效输入,其中变量 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();
}

}

注释行是所有不成功的尝试,它们要么导致没有throw1,要么导致以下错误消息:

regular expression error

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

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


1。当使用包含某些符号的无效名称来初始化对象时。

最佳答案

主要问题是某些特殊字符需要使用 \ 字符进行转义,以便正则表达式引擎将其读取为自身(即 * 是一个特殊的标记,意思是匹配 0 个或多个先前的标记)。这意味着您不仅需要转义通常的 ' && " 字符,还需要为其他字符添加 \ 字符前缀

你可以通过以下模式实现你想要的:

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

关于c++ - 使用正则表达式检查输入有效性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33488675/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com