我构造一个字符串来表示我的整个Gomoku游戏板(例如,5x5),其中0表示空,1或2表示黑色或白色。
在每一行之间放置一个字符串"x“以分隔行。
std::string state = "00000x012122x00100x00222x010201"我要做的是检查当前球员的水平的匹配值为3(稍后我将处理垂直和对角线);比方说,白色,所以我在字符串中依次寻找32s的匹配,而只有32s。
Gomoku不允许过线,这意味着正则表达式不能匹配4或更多。
下面是我对这个问题的尝试:
bool Game::check_horizontal(std::string state)
// Checks if the current_player (stored in the class) has won horizontally.
{
std::string pattern = "(" + std::to_string(current_player) + "{3})"; // Current player is white by default.
std::regex reg1(pattern);
if (regex_search(state, reg1) == true)
{
std::cout << "Match! Someone has won." << std::endl;
return true;
}
else
{
std::cout << "No match... keep going." << std::endl;
return false;
}
}到目前为止,代码似乎按照上面的状态工作,但是如果我要寻找的东西有4个或更多,它就会保持匹配。如果我在第4行再添加2,在第2列中,它仍然是匹配的。
我的正则表达式或正则表达式的用法有问题吗?
发布于 2015-06-27 21:24:36
虽然我不认为使用regex进行此操作有什么意义,但下面的模式与3完全匹配:
std::string playerStr = std::to_string(current_player);
std::string pattern = "(^|[^" + playerStr + "])(" + playerStr + "{3})($|[^" + playerStr + "])";https://stackoverflow.com/questions/31093441
复制相似问题