phySical
phySical

Reputation: 65

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

I'm struggling with this C++ compiler error to get my regex_match() function to work. The code:

#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;
}

I want to check if n contains at least one of the characters I wrote in the regex r().

Btw, for people learning regex I've found the great website: https://regex101.com.

Any sugestions? Thx!!

Upvotes: 1

Views: 5115

Answers (1)

krzaq
krzaq

Reputation: 16421

test is a character. There's no overload of std::regex_match for a character.

I'm not sure if you want to check every character against the list of characters or just the first one. If it's them all, you can use 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;
    }
}

Based on the additional comments I think I understand what you wanted: check if the string n contained any of the "illegal" characters. For this task std::regex_search is better suited:

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

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

Upvotes: 2

Related Questions