Create a gist now

Instantly share code, notes, and snippets.

Embed
What would you like to do?
测试书写的正则表达式。通过预先设定好测试用例,来测试书写的正则表达式是否符合预期要求。
// RegexpWritingTester.cpp: 定义控制台应用程序的入口点。
// 测试用例输入格式:
// 匹配数据
// 是否应该匹配(1/0)
#include <iostream>
#include <regex>
#include <string>
#include <cstdlib>
#include <vector>
using namespace std;
/*
DEBUG:
0 - 关闭调试
1 - 开启内置测试数据
2 - 开启内置测试数据 + 内置正则
*/
#ifdef _DEBUG
#define DEBUG 0
#endif
//class Test;
//struct TestException : public exception
//{
// Test& test;
// template <typename ...argsType>
// TestException(Test test, argsType... args)
// : test(test), exception(args...)
// {}
//};
class Test {
public:
string text;
bool shall;
static void resetCount() {
Test::passed = 0;
}
bool Run(const regex& re) const{
int& cnt = this->passed;
++cnt;
if (shall == regex_match(text, re))
{
clog << "test " << cnt << " passed! " << endl;
return true;
}
else {
clog << "------------------------------------------" << endl;
cerr << "TEST " << cnt << " FAILED! " << endl;
cerr << "text: " << text << endl;
cerr << "shall: " << boolalpha << shall << endl;
//throw TestException(Test(*this), "testCase failed");
return false;
}
}
private:
static int passed;
};
int Test::passed = 0;
template<class ...isArgs>
auto operator>>(basic_istream<isArgs...>& is, Test& testcase)
->decltype(is)&
{
{
if (cin.peek() == '\n')
{
cin.ignore();
}
getline(cin, testcase.text, '\n');
}
string shall;
is >> shall;
testcase.shall = (shall == "true" || atoi(shall.c_str())>0);
return is;
}
vector<Test> GetTestCase() {
#if DEBUG>=1
return vector<Test> {
{ "123a123b", false },
{ "123", true },
{ "123a123", true },
{ "b123", true },
{ "aa123", false }
};
#endif // DEBUG>=1
vector<Test> tests;
Test test;
while (cin >> test)
{
tests.push_back(move(test));
}
cin.clear();
return tests;
}
bool tryRegexp(const regex& re, const vector<Test>& tests) {
Test::resetCount();
for (auto&& test : tests) {
//try {
if (!test.Run(re))
{
break;
return false;
}
//}
//catch (TestException& e) {
// cerr << "fuck!" << e.what() << endl;
// cerr << e.test.text << " " << e.test.shall;
// return false;
//}
}
return true;
}
void init() {
atexit([]() {
clog << "--------------------" << endl;
clog << "EXITED" << endl;
clog.flush();
cin.get();
});
}
int main() {
init();
cout << "Begin to input test case (EOF to finish):" << endl;
vector<Test> tests = GetTestCase();
cout << "Begin to input regexp:" << endl;
#if DEBUG==2
tryRegexp(regex(R"(^[^ab]*[ab]?[^ab]*$)"), tests);
#else
string regexpStr;
while (cin >> regexpStr)
{
try {
tryRegexp(regex(regexpStr), tests);
}
catch (regex_error& e)
{
cerr << "regex_error: " << e.what() << endl;
}
}
#endif // DEBUG==2
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment