gpt4 book ai didi

c++ - 使用正则表达式进行输入验证

转载 作者:行者123 更新时间:2023-11-28 02:37:39 25 4
gpt4 key购买 nike

我知道以下不是最有效的实现(毕竟我可以在 main() 中运行 regex_match() )但它应该仍然有效,至少从我有限的理解来看是这样。

我正在尝试在 C++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" 相同(您应该会看到有关无法识别的转义序列的编译器警告),而 "\\s" 代表两个字符,反斜杠和's'

将所有反斜杠加倍,或者为您的正则表达式使用原始字符串文字,如

string  diceexpr = R"(^\s*\d{1,}d\d{1,}\s*$)";

关于c++ - 使用正则表达式进行输入验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26965672/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com