为了让我的 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
没有重载对于 char
acter.
我不确定您是要根据字符列表检查每个字符还是只检查第一个字符。如果是全部,您可以使用 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/