Composing a complete word with regex.h

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.h> #include <stdio.h> int main() { regex_t rexp; int rv = regcomp(&rexp, "\\bbananas\\b|\\bpajamas\\b", REG_EXTENDED | REG_NOSUB); if (rv != 0) { printf("Abandon hope, all ye who enter here\n"); } regmatch_t match; int diditmatch = regexec(&rexp, "bananas", 1, &match, 0); printf("%d %d\n", diditmatch, REG_NOMATCH); } 

and he printed 1 1 as if there was no coincidence. What happened? I also tried \bbananas\b|\bpajamas\b for my regex, and that didn't work either.

I asked for matching whole words using regex about std :: regex, but std :: regex is awful and slow, so I'm trying regex.h.

+6
source share
3 answers

The POSIX standard does not specify the word boundary syntax, nor the look-behind and look-forward syntax (which can be used to emulate word boundaries) for both BRE and ERE. Therefore, it is not possible to write a regular expression with layers that works on different platforms compatible with POSIX .

For a portable solution, you should use PCRE or Boost.Regex if you plan on C ++ code.

Otherwise, you are stuck in an intolerable solution. If you are fine with this limitation, there are several alternatives:

+1
source

Conrad left a big answer that solved my problem, but somehow disappeared, so I can’t accept it. Here is the code that printed correctly for posterity:

 #include <regex.h> #include <stdio.h> int main() { regex_t rexp; int rv = regcomp(&rexp, "[[:<:]]bananas[[:>:]]|[[:<:]]pajamas[[:>:]]", REG_EXTENDED | REG_NOSUB); if (rv != 0) { printf("Abandon hope, all ye who enter here\n"); } regmatch_t match; int diditmatch = regexec(&rexp, "bananas", 1, &match, 0); printf("%d %d\n", diditmatch, REG_NOMATCH); } 
0
source

Using

s == "balances" || s == "pajamas"

instead of s is std::string .

Regular expressions can recompile a simple solution. Avoid them, in particular if a fixed match is required.

-1
source

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


All Articles