c++ - C++ regex_replace 不替换字符串
问题描述
我是 C++ 的新手。我正在尝试学习字符串替换。
我正在编写一个简短的(应该是教程)程序来更改目录名称。
例如,我想用“/illumina/runs”更改目录名称开头的“/home”:
#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;
}
我正在关注来自http://www.cplusplus.com/reference/regex/regex_replace/的示例,但我不明白为什么这没有改变。
万一我写的东西没有意义,Perl 等价物是$dir =~ s/^\/home/\/illumina\/runs/
如果这有助于更好地理解问题
为什么这段代码没有像我告诉它的那样改变字符串?如何让 C++ 更改字符串?
解决方案
std::regex_replace
不修改其输入参数。它产生一个新std::string
的作为返回值。例如,请参见此处:https ://en.cppreference.com/w/cpp/regex/regex_replace (您的呼叫使用过载编号 4)。
这应该可以解决您的问题:
b2_dir = std::regex_replace(b2_dir, std::regex("^/home"), "/illumina/runs");