1

I construct a string that represents my entire Gomoku game board (5x5 for example), where 0 indicates empty, and 1 or 2 indicates black or white.

A string "x" is placed between each row to separate the rows.

std::string state = "00000x012122x00100x00222x010201"

What I'm trying to do is check for a match of 3 for the current player horizontally (I will deal with vertical and diagonal later); let's say, white, so I am looking for a match of three 2's sequentially in the string, and only three 2's.

Gomoku does not allow overline, which means the regular expression cannot match 4 or more.

Here is my attempt at the problem:

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;
    }
}

So far it seems that the code works as intended for the state above, but it keeps matching if there are 4 or more of what I'm looking for. If I added another 2 on the 4th row, in the 2nd column, it will still match.

Is there a problem with my regular expression, or my usage of regex?

1 Answers1

2

Though I don't see a point in using regex for this, here's a pattern which matches exactly 3:

std::string playerStr = std::to_string(current_player);
std::string pattern =  "(^|[^" + playerStr + "])(" + playerStr + "{3})($|[^" + playerStr + "])";
Anton Savin
  • 40,838
  • 8
  • 54
  • 90
  • Thank you for helping me with the regular expression. The reason why I am doing it with regex is because I am following another stackoverflow recommendation. I'm trying to avoid excessive loops. http://stackoverflow.com/questions/4312391/board-game-win-situation-searching-algorithm – Hitsumaru XD Jun 30 '15 at 03:58