Inquisitive Idiot
Inquisitive Idiot

Reputation: 422

Whole-word matching using regex

I want a C++ regex that matches "bananas" or "pajamas" but not "bananas2" or "bananaspajamas" or "banana" or basically anything besides those exact two words. So I did this:

#include <regex>

int main(int argc, char** argv) {
  static const std::regex bp = std::regex("\bbananas\b|\bpajamas\b");
  printf("%d\n", std::regex_match("bananas", bp));
}

Except it printed 0! What gives? /\bbananas\b|\bpajamas\b/.test('bananas') gives me true in Javascript so what's different about C++?

Upvotes: 6

Views: 3122

Answers (2)

You should not use a regular expression for this. If you want to find out whether a string is one of two words, just use a straightforward equality comparison:

if (str == "bananas" || str == "pajamas") {
    // OK
}

If you have more possibilities, you can use some sort of a set:

const std::unordered_set<std::string> words {
    "bananas",
    "pajamas",
    "papayas"
};

if (words.find(str) != words.end()) {
    // OK
}

Upvotes: 0

Ahosan Karim Asik
Ahosan Karim Asik

Reputation: 3299

Regex string should have \bbananas\b|\bpajamas\b. but in c++, "\bbananas\b|\bpajamas\b" return bbananasb|bpajamasb. for this reason, you have to use extra \ with \ like "\\bbananas\\b|\\bpajamas\\b"

Upvotes: 5

Related Questions