首页 > 解决方案 > std::regex 不匹配

问题描述

我有一个regex101可以正常工作的正则表达式:

在此处输入图像描述

正如预期的那样,有 2 场比赛。

现在我想用 std 的regex_token_iterator拆分相同的内容:

const std::string text = "This is a test string [more or less] and here is [another].";

const std::regex ws_re("\(?<=\[)(.*?)(?=\])\gm"); // HOW TO WRITE THE ABOVE REGEX IN HERE?

std::copy( std::sregex_token_iterator(text.begin(), text.end(), ws_re, -1),
           std::sregex_token_iterator(),
           std::ostream_iterator<std::string>(std::cout, "\n"));

这编译得很好,但没有任何东西打印到标准输出。

我认为正则表达式必须以其他方式编写,您能指出我的错误吗?

标签: c++regexparsingsplit

解决方案


您可以使用

const std::regex ws_re(R"(\[([^\]\[]*)\])");

此外,请确保通过将1作为最后一个参数传递给std::sregex_token_iterator而不是-1-1在拆分时使用)来提取第 1 组值。

R"(\[([^\]\[]*)\])"是定义\[([^\]\[]*)\]正则表达式模式的原始字符串文字。它匹配

  • \[- 一个[字符
  • ([^\]\[]*)[- 第 1 组:除and之外的任何零个或多个字符]
  • \]- 一个]字符。

请参阅C++ 演示

#include <string>
#include <iostream>
#include <regex>
using namespace std;

int main() {
    const std::string text = "This is a test string [more or less] and here is [another].";
    const std::regex ws_re(R"(\[([^\]\[]*)\])");
    std::copy( std::sregex_token_iterator(text.begin(), text.end(), ws_re, 1),
           std::sregex_token_iterator(),
           std::ostream_iterator<std::string>(std::cout, "\n"));
    
    return 0;
}

推荐阅读