Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find and replace using std::regex_replace() function in cpp

Tags:

c++

regex

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?

like image 608
kishoredbn Avatar asked Oct 28 '15 06:10

kishoredbn


1 Answers

Your code is fine with the exception of 2 points:

  • Regex - you have unescaped $ that means end of string, \b word boundary before and after $ that requires a word character to appear right next to the $ symbol.
  • There is no signature for 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

like image 146
Wiktor Stribiżew Avatar answered Nov 09 '22 22:11

Wiktor Stribiżew