C++ 错误 : no matching function for call to 'regex_match()'

标签 c++ regex match

为了让我的 regex_match() 函数正常工作,我正在努力解决这个 C++ 编译器错误。代码:

#include <iostream>
#include <string>
#include <regex>
using namespace std;

struct Person {
    Person(string name, int age)
        : n{name}, a{age}
    {
        regex r("^([!:*&%#@^\\[\\]\"\'])+");             // :*[]"'&^%#@!
        for(char test : n) {
            cout << "Character: " << test;
            if(regex_match(test, r)) {
                cout << endl << "Error: wrong character!" << endl;
            }
        }
    }
    string n;
    int a;
};

int main() {
    Person Goofy("Goofy",11);
    return 0;
}

我想检查 n 是否至少包含我在正则表达式 r() 中写入的字符之一。

顺便说一句,对于学习正则表达式的人,我找到了一个很棒的网站:https://regex101.com .

有什么建议吗?谢谢!!

最佳答案

test 是一个字符。 std::regex_match 没有重载对于 character.

我不确定您是要根据字符列表检查每个字符还是只检查第一个字符。如果是全部,您可以使用 std::any_of :

char const constexpr m[] = R"(:*[]"'&^%#@!)";
for(char test : n) {
    if(any_of(begin(m), end(m), [test](char c){ return c == test; })) {
        cout << endl << "Error: wrong character!" << endl;
    }
}

根据附加评论,我想我明白您想要什么:检查字符串 n 是否包含任何“非法”字符。对于此任务 std::regex_search更适合:

regex r{R"([:*\[\]"'&^%#@!])"};

if(regex_search(n, r)){
    cout << endl << "Error: wrong character!" << endl;
}

关于C++ 错误 : no matching function for call to 'regex_match()' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40053813/

相关文章:

c++ - 将 .end() 与值进行比较

c++ - 如果 'throw' 未能为异常对象分配内存会怎样?

密码的正则表达式

Javascript RegExp 匹配返回太多

c++ - 文件重定向运算符 ">"不适用于 CreateProcess() API

c++ - 错误 : ‘IOV_MAX’ undeclared (first use in this function)

ruby - 如何捕获正则表达式中某个单词之前的几个单词

c# - 正则表达式按模式查找并仅替换一部分

php - 如何不只匹配一个正则表达式

c# - 拆分一个由前导数字和之后的所有内容组成的字符串