正则表达式替换捕获,然后进行数字分隔

时间:2019-01-17 18:21:50

标签: c++ regex

我正在尝试学习在C ++中使用正则表达式,并且得到了以下代码:

std::string s("21\n");
std::regex e("\\b(2)1");   

std::cout << std::regex_replace(s, e, "${1}0 first");

我想转身

  

21

进入

  

先20

但是{}似乎不像C#一样分隔捕获'$ 1'。那我该怎么用?

总体上有人可以指出我C ++正则表达式库文档吗?看来我找不到。 也许有人可以指向我提供一个具有完整文档的更好的图书馆?

1 个答案:

答案 0 :(得分:3)

C ++不允许使用${1}语法。通常,这可能是个问题,因此有时您必须use a callback instead

但是,在这种情况下,您很幸运,因为后向引用标识符最多为两位数,所以使用$01 you're safe

#include <string>
#include <regex>
#include <iostream>

int main()
{
    std::string s("21\n");
    std::regex e("\\b(2)1");   

    std::cout << std::regex_replace(s, e, "$010 first") << '\n';
}

// Output: 20 first

live demo

关于文档cppreference has most of the facts,但是老实说std::regex的可用文档与功能本身一样深奥。

相关问题