std::regex_replace specify replace sequence?

I'm just learned the basics of Regular Expressions a few days ago, so please forgive me if I make some obvious mistakes.
I want regex_replace to match the whole expression, but only replace part of it. For example, I want to replace all "!"s with "?"s, but only if there is one letter or more before the "!", so if the input's "hello, world!" the output would be "hello, world?", but if the input is "hello, world !" it would remain the same.
This is what I have so far:
1
2
3
4
5
6
int main() {
    std::regex r("[A-Za-z]+(!)");
    std::string target("hello, world!");
    std::cout << std::regex_replace(target, r, "?") << std::endl;
    return 0;
}

But the problem is regex_replace ignores my capture groups and just replaces the whole thing, so I get "hello, ?" as the output. Is there a way I can make it only replace the "!", but match the whole sequence?


(Actually, I have made a calculator, and want to make it accept things like "x!". So I was thinking, with regex, can you replace "x!" with "fact(x)"? If yes, can you show me the code to do so? Any help would be appreciated. Thanks.)
The replacement string has its own syntax:
The default is ECMAScript replacement syntax:
http://ecma-international.org/ecma-262/5.1/#sec-15.5.4.11

The atlernative is format_sed: http://pubs.opengroup.org/onlinepubs/9699919799/utilities/sed.html#tag_20_116_13_03

If you want to replace ! with ?, you don't even need to read those:

1
2
3
4
5
6
7
8
#include <iostream>
#include <regex>

int main() {
    std::regex r("!");
    std::string target("hello, world!");
    std::cout << std::regex_replace(target, r, "?") << '\n';
}

demo : http://coliru.stacked-crooked.com/a/9ea171932b7f0682

(or, to use something closer to the original,
std::regex r("([A-Za-z]+)!"); and std::regex_replace(target, r, "$1?") : http://coliru.stacked-crooked.com/a/ac44e73b5fe586d6

as for why, see docs on std::regex_replace:
http://www.cplusplus.com/reference/regex/regex_replace
http://en.cppreference.com/w/cpp/regex/regex_replace

Last edited on
Thanks!
Topic archived. No new replies allowed.