lundi 29 juin 2015

Whole-word matching with regex.h


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.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 it printed 1 1 as if there wasn't a match. What happened? I also tried \bbananas\b|\bpajamas\b for my regex and that failed too.

I asked Whole-word matching regex in C++ about std::regex, but std::regex is awful and slow so I'm trying regex.h.


Aucun commentaire:

Enregistrer un commentaire