用于检查Gomoku获胜条件的C++正则表达式
C++ regex for checking Gomoku win condition
我构造了一个字符串,表示我的整个Gomoku游戏板(例如5x5),其中0表示空,1或2表示黑色或白色。
在每一行之间放置一个字符串"x"以分隔行。
std::string state = "00000x012122x00100x00222x010201"
我想做的是检查当前玩家水平的3匹配(稍后我将处理垂直和对角线);比方说,白色,所以我在字符串中寻找三个2的匹配,而只有三个2。
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,它仍然会匹配。
我的正则表达式或regex的使用有问题吗?
虽然我认为使用regex没有任何意义,但这里有一个与3:完全匹配的模式
std::string playerStr = std::to_string(current_player);
std::string pattern = "(^|[^" + playerStr + "])(" + playerStr + "{3})($|[^" + playerStr + "])";
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- C++正则表达式无限循环
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 定义有趣的宏和正则表达式在Z3 C++绑定
- 带有多个字符分隔符的正则表达式
- C++ 使用增强正则表达式库时断言崩溃
- 有人可以帮助我处理正则表达式吗?
- 使用正则表达式获取大括号块的列表
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- 组合正则表达式部分使用 | 不起作用的 C++
- 为什么C++正则表达式这么慢?
- 如何使HTML5电子邮件验证正则表达式在C++中工作?
- 在C++中实现正则表达式
- C++正则表达式替换整个单词
- 用C++编写正则表达式的正确方法是什么?
- 如何从Stroustrup的C++书中解释这个正则表达式?
- 为什么这个正则表达式C++在括号表达式中抛出无效范围异常?
- C++:匹配正则表达式,什么是匹配?
- C++:正则表达式匹配代码,打印多个匹配项?