0

I'm trying to learn using regex in C++ and I got this code:

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

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

I wanna turn

21

into

20 first

but {} seem not to separate capture '$1' like in C#. What should I use then?

And overall can someone point me to C++ regex library documentation? It seems I can't find one. Or maybe somebody can point me to a better library with full documentation?

Aleksandr
  • 33
  • 4
  • "can point me to a better library with full documentary?" boost has decent documentation and most of it applies to std as it came there from boost. Anyway please edit your question to contain [mcve] – Slava Jan 17 '19 at 18:25

1 Answers1

3

C++ doesn't permit the ${1} syntax. In general, that can be a problem, so sometimes you have to use a callback instead.

In this particular case, though, you're in luck because the backreference identifier is at most two digits, so with $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)

As for documentation, cppreference has most of the facts, but in all honesty the available documentation for std::regex is about as esoteric as the feature itself.

Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • $010 is really the case for this, thank you. I'll mark your post as an answer. But I fear there will rise more and more questions regarding regex as I can't simply understand syntax of writing it. – Aleksandr Jan 17 '19 at 18:31
  • 1
    @Aleksandr If your questions are about forming a valid _pattern_, there are loads of good resources for that all over the web. If it's about the C++ technology surrounding it, feel free to ask again (after consulting the reference, of course): you're certainly [not the only one](https://stackoverflow.com/q/54237547/560648) asking questions about `std::regex` here! – Lightness Races in Orbit Jan 17 '19 at 18:32