Compose whole words using regular expressions

I want a C ++ regular expression that matches “bananas” or “pajamas” but not “bananas2” or “banapaspayamasam” or “bananas” or nothing at all other than these two exact 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 that it printed 0! What gives? /\bbananas\b|\bpajamas\b/.test('bananas') gives me true in Javascript, so what is different from C ++?

+4
source share
2 answers

The regex string must have \bbananas\b|\bpajamas\b . but in C ++, "\bbananas\b|\bpajamas\b" return bbananasb|bpajamasb . for this reason you need to use extra \ c \ like "\\bbananas\\b|\\bpajamas\\b"

+2
source

You should not use regex for this. If you want to know if a string is one of two words, just use direct equality comparison:

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

If you have more options, you can use some kind of set:

 const std::unordered_set<std::string> words { "bananas", "pajamas", "papayas" }; if (words.find(str) != words.end()) { // OK } 
0
source

Source: https://habr.com/ru/post/989937/


All Articles