Er Kandarp Patel Er Kandarp Patel - 4 months ago 10
C++ Question

C++ How to Extract Substring between two same symbols

I am new to c++ programming. I need some help,

I have string :
---- Input : "Name : $$ Enter Your Name2 $$"
I want to extract string between $$ symbols including symbols :
---- Output : "$$ Enter Your Name2 $$"

Please help me.


Regular Expression are very useful in this case.

C++11 has regex library.

#include <string>
#include <regex>

std::string parse_string(const std::string& str) {
  static const std::string REGEX_STR = R"__(\$\$(\w|\W)*\$\$)__";
  std::regex regex(REGEX_STR);
  std::smatch regex_iterator;
  if (std::regex_search(str, regex_iterator, regex)) {
    return regex_iterator.str();
  return std::string("");

The code can be improved but it should represent a good starting point. Specific case should be handled, for example: more $$*$$ in a string, etc...

R"__(\$\$(\w|\W)*\$\$)__"; is a raw string in order to make more readable the regex.