1

I have a list of strings and I want to create a regex that literally defines matches. I thought that it is enough just to list all valid strings separated with |, as in the snippet below:

#include<iostream>
#include<regex>

int main(){
  std::regex regex("one|two|three|four");
  std::vector<std::string> candidates = {"one", "two", "three", "four", "five"};

  for(auto it : candidates){
    if(std::regex_match(it, regex)){
      std::cout << it << " matches regex " << std::endl;
    }
  }
}

I expected to get following output:

$one matches regex
$two matches regex
$three matches regex
$four matches regex

Instead, only the two first candidates were a hit. I found out that it would work if I used parentheses, like this:

std::regex regex("((one|two)|three)|four");

But I would like to avoid it, because such a list can grow quite a lot.

Patryk
  • 1,421
  • 8
  • 21
  • 5
    [Which implementation?](http://coliru.stacked-crooked.com/a/3b103f034fa5ba04) – chris Mar 23 '15 at 15:06
  • 1
    http://ideone.com/po3qwn – Ivaylo Strandjev Mar 23 '15 at 15:19
  • I used g++ (Ubuntu 4.8.2-19ubuntu1) 4.8.2. It seems that we've found the answer – Patryk Mar 23 '15 at 15:20
  • @Patryk, GCC did not have a working implementation of regex until 4.9. – chris Mar 23 '15 at 15:29
  • http://stackoverflow.com/questions/12530406/is-gcc-4-7-and-gcc-4-8-buggy-about-regular-expressions would be a better duplicate in my opinion since it references the same minor versoion of gcc and mentions that regex is now implemented in 4.9 and also explains why there is no compilation error. – eerorika Mar 23 '15 at 15:30

0 Answers0