1

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!!

1 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

5 Comments

I'm a newbie, can you explain please? Converting the char test to a string didn't work..
I edited with an example. regex_match is supposed to match a string against a regex, not a single character. There's not much more than that to it.
@m3n741 if you could tell me what exactly you're trying to achieve I could help you better, I hope.
std::find_first_of(n.begin(), n.end(), m.begin(), m.end()) is equivalent to the test in your first snippet and doesn't need the loop or the lambda.
I wanted to check if the string n has any of the regex r signs in it and if I could use regex_match for that. Thank you for the quick answer :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.