Я знаю, что следующая не самая эффективная реализация (я могу, в конце концов, запустить regex_match() прямо в main()), но она все равно должна работать, по крайней мере, из моего ограниченного понимания.
Я пытаюсь использовать в С++ 11 для проверки ввода данных для dicerolls. Я использовал expresso для создания регулярных выражений, и он точно проверяет его в expresso. Почему это не сработает в этом коде?
#include <iostream>
#include <string>
#include <regex>
bool regexValidate (string expr, string teststring)
{
regex ex(expr);
if (regex_match(teststring,ex)) {
return true;
cout << "true";
} else if (regex_match (teststring,regex("^\s*\d*d\d*\s*$"))) {
return true;
cout << "true";
}
return false;
}
int main()
{
char choice; // menu option selected by user
bool isExit = false; // Is the user ready to exit?
// test code
string diceexpr = "^\s*\d{1,}d\d{1,}\s*$";
string teststr = "10d10";
string teststr1 = "1d10";
string teststr2 = " 10d10 ";
cout << teststr << " is ";
if (regexValidate(diceexpr,teststr)) {
cout << " valid!" << endl;
} else {
cout << " invalid!" << endl;
}
cout << teststr1 << " is ";
if (regexValidate(diceexpr,teststr1)) {
cout << " valid!" << endl;
} else {
cout << " invalid!" << endl;
}
cout << teststr2 << " is ";
if (regexValidate(diceexpr,teststr2)) {
cout << " valid!" << endl;
} else {
cout << " invalid!" << endl;
}
return 0;
}
Пример вывода:
10d10 is invalid!
1d10 is invalid!
10d10 is invalid!
RUN SUCCESSFUL (total time: 291ms)
ОБНОВИТЬ
Исправил мой код и изменил его, чтобы использовать библиотеку boost для регулярных выражений.
#include <iostream>
#include <string>
#include <boost/regex.hpp>
using namespace std;
bool regexValidate (string expr, string teststring)
{
boost::regex ex(expr);
if ( boost::regex_match (teststring,ex) ) {
cout << "true";
return true;
//} else if (regex_match (teststring,regex("^\s*\d*d\d*\s*$"))) {
// cout << "true";
// return true;
}
return false;
}
int main()
{
string diceexpr = "^\\s*\\d{1,}d\\d{1,}\\s*$";
string teststr = "10d10";
string teststr1 = "1d10";
string teststr2 = " 10d10 ";
cout << teststr << " is ";
if (regexValidate(diceexpr,teststr)) {
cout << " valid!" << endl;
} else {
cout << " invalid!" << endl;
}
cout << teststr1 << " is ";
if (regexValidate(diceexpr,teststr1)) {
cout << " valid!" << endl;
} else {
cout << " invalid!" << endl;
}
cout << teststr2 << " is ";
if (regexValidate(diceexpr,teststr2)) {
cout << " valid!" << endl;
} else {
cout << " invalid!" << endl;
}
return 0;
}
Учитывая следующий результат:
terminate called after throwing an instance of 'std::regex_error'
what(): regex_error
RUN FAILED (exit value 1, total time: 1s)
string diceexpr = "^\s *\d {1,} d\d {1,}\s * $";
Это не делает то, что вы думаете. В строковом литерале "\s"
совпадает с "s"
(вы должны видеть предупреждения компилятора о непризнанных escape-последовательностях), в то время как "\\s"
представляет два символа, обратную косую черту и 's'
.
Уберите все обратные косые черты, или используйте строковый литерал для регулярного выражения, как в
string diceexpr = R"(^\s*\d{1,}d\d{1,}\s*$)";