使用正则表达式检查输入的有效性

Using regex to check input validity?

本文关键字:有效性 输入 检查 正则表达式      更新时间:2023-10-16

我正在尝试检测无效输入,其中变量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个或多个匹配)。这意味着您不仅需要转义常见的' && "字符,还需要在其他字符前面加上字符

你可以用这样的模式来实现你想要的

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