【问题标题】:std::regex not matchingstd::regex 不匹配
【发布时间】:2021-04-16 15:18:42
【问题描述】:

我有一个 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"));

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

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

【问题讨论】:

  • \ 必须转义或使用原始字符串文字。
  • 尝试使用\\(?&lt;=\\[)(.*?)(?=\\])\\gm。仍然没有打印任何内容。
  • 或者使用原始字符串。
  • 你不应该在正则表达式中有\gm
  • 为什么第一个括号被转义了,而其他的不是?

标签: c++ regex parsing split


【解决方案1】:

你可以使用

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

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

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

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

C++ demo

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

【讨论】:

  • 这行得通,我可以在正则表达式中以某种方式使用前瞻吗?
  • @Daniel 您可以在std::regex 中使用前瞻,但不能使用后瞻。否则,使用boost::regex,那么您将能够使用所有环视。
【解决方案2】:

您需要使用\\ 转义\。此外,\gm\(开头)应删除为:(?&lt;=\\[)(.*?)(?=\\])

【讨论】:

  • 你说\gm应该被删除,但你没有删除它。
  • 哦,我明白了,括号不应该被转义。可以试试吗:(?&lt;=\\[)(.*?)(?=\\])
猜你喜欢
  • 2018-12-01
  • 1970-01-01
  • 2018-08-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-07-01
  • 1970-01-01
相关资源
最近更新 更多