con
con

Reputation: 6093

C++ regex_replace not replacing string

I'm a newbie with C++. I'm trying to learn string replacement.

I'm writing a short (supposed to be a tutorial) program to change directory names.

For example, I want to change "/home" at the beginning of a directory name with "/illumina/runs" thus:

#ifdef WINDOWS
#include <direct.h>
#define GetCurrentDir _getcwd
#else
#include <unistd.h>
#define GetCurrentDir getcwd
#endif

#include<iostream>
#include <string>
#include <regex>
#include <iterator>
using namespace std;

std::string get_current_dir() {
   char buff[FILENAME_MAX]; //create string buffer to hold path
   GetCurrentDir( buff, FILENAME_MAX );
   string current_working_dir(buff);
   return current_working_dir;
}

int main() {
   string b2_dir = get_current_dir();
   std::regex_replace(b2_dir, std::regex("^/home"), "/illumina/runs");
   cout << b2_dir << endl;
   return 0;
}

I'm following an example from http://www.cplusplus.com/reference/regex/regex_replace/ but I don't see why this isn't changing.

In case what I've written doesn't make sense, the Perl equivalent is $dir =~ s/^\/home/\/illumina\/runs/ if that helps to understand the problem better

Why isn't this code altering the string as I tell it to? How can I get C++ to alter the string?

Upvotes: 1

Views: 558

Answers (1)

AVH
AVH

Reputation: 11516

std::regex_replace does not modify its input argument. It produces a new std::string as a return value. See e.g. here: https://en.cppreference.com/w/cpp/regex/regex_replace (your call uses overload number 4).

This should fix your problem:

b2_dir = std::regex_replace(b2_dir, std::regex("^/home"), "/illumina/runs");

Upvotes: 6

Related Questions