0

I'm trying to use the C++ regex library. I would expect "aaaaa" to match "[a-z]+", but that is not happening. The code below is exactly that which I am running. When run, it prints nothing. (I would expect it to print "Match!")

#include <regex>
#include <iostream>

int main(int argc, char **argv) {
  std::regex r("[a-z]+", std::regex_constants::basic);

  if ( std::regex_match("aaaaa", r)) {
    std::cout << "Match!" << std::endl;
  }
  return 0;
}

This is my build command:

$ g++ a.cc  -std=c++11

I'm very confused. What do I need to do to make repetitions play nice with bracket expressions?

Notes:

I've tried a few experiments:

  • "[:lower:]+" does not match "aaaaa"
  • "[a-z]" matches the string "a"
  • "a+" matches "aaaaa"
  • "a{3,20}" does not match "aaaaa"
  • Switching to egrep, grep, extended or awk made no difference.
  • Switching to ECMAScript resulted in an exception.
azani
  • 486
  • 3
  • 14

1 Answers1

0

I'm going to take a guess that you're using gcc 4.x or earlier.

Although it included a <regex> header, and had declarations/definitions for functions with the right names, much of it was originally written as a proof of concept, so although it (apparently) did work for some regexes, it was broken enough that you can't depend on its working in general.

Using reasonably current implementations, (e.g., MSVC 2017, gcc 7.1, Clang 3.8), I get a result of "Match!" from the following code:

#include <regex>
#include <iostream>

int main(int argc, char **argv) {
    std::regex r("[a-z]+");

    if (std::regex_match("aaaaa", r)) {
        std::cout << "Match!" << std::endl;
    }
}

If you really need to use regexes can you can't update your compiler, you might want to consider using Boost regex instead.

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111