为什么多次交替在c ++ std :: regex中不起作用

时间:2015-03-23 15:04:38

标签: c++ regex c++11

我有一个字符串列表,我想创建一个字面上定义匹配的正则表达式。我认为仅列出用|分隔的所有有效字符串就足够了,如下面的代码段所示:

#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;
    }
  }
}

我希望得到以下输出:

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

相反,只有两个第一候选人受到了打击。我发现如果我使用括号,它会起作用,如:

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

但是我想避免它,因为这样的列表可以增长很多。

0 个答案:

没有答案