I am working on a project where I need to find words starting with $< and ending with >$ and replace with it with a word stored in a variable.
Example
string a ="hello";
string b = "Fellow $<world>$, full of $<smart>$ people"
std::cout<<std::regex_replace(b, "\\b($<)([^ ]*)(>$)\\b", a); //should print "Fellow hello, full of hello people"
but seems like this is not possible directly.
How can I work around this?
Your code is fine with the exception of 2 points:
$ that means end of string, \b word boundary before and after $ that requires a word character to appear right next to the $ symbol.regex_replace like the one you used.So, the correct regex is
\$<[^<>]*>\$
The \$ matches a literal $, then follows a literal <, then 0 or more characters other than < and > up to the literal >$.
In C++, you can use raw strings (R"()") to declare regex objects, it will relieve the pain of escaping metacharacters twice.
See IDEONE demo:
string a ="hello";
string b = "Fellow $<world>$, full of $<smart>$ people";
std::cout<<std::regex_replace(b, std::regex(R"(\$<[^<>]*>\$)"), a);
Output: Fellow hello, full of hello people
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With