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?

1
  • "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 minimal reproducible example Commented Jan 17, 2019 at 18:25

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

$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 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 asking questions about std::regex here!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.