搜索/替换boost正则表达式

search/replace boost regex C++

本文关键字:正则表达式 boost 替换 搜索      更新时间:2023-10-16

我有一个正则表达式替换问题,我似乎无法找出替换文件路径的一些配置参数。

到目前为止我写的是:

文件路径的正则表达式可能不完美,但它似乎工作得很好。

regex: ^(?<path>[^\/*?<>|]+)\\(?<filename>.+)\.(?<ext>.mp4$)

文件名匹配结果名称:$2

所以这是做的是搜索文件列表,其中扩展名为mp4,并使用配置的匹配结果,它将返回作为"文件名"。

目标字符串示例,

\\foldermusichello.mp4

result filename = "hello"

我想做的是能够从正则表达式匹配中获取结果,并能够通过配置的设置替换文件/扩展名/路径的名称。

因此,如果有人想要所有匹配的结果替换文件名为"goodbye",我该如何实现这一点。这是我现在拥有的。

std::string sz_regex_pattern("^(?<path>[^/*?<>|]+)\(?<filename>.+).(?<ext>.mp4$)");
boost::cmatch rm;
boost::regex pattern(sz_regex_pattern, regex::icase|regex_constants::perl);
std::string complete_file_name_path = "\foldermusichello.mp4";
bool result = boost::regex_match(complete_file_name_path , rm, pattern);
std::string old_filename= rm.format("$2"); // returns the name of the file only

什么似乎工作,但限制它的文件名,其中文件夹不相同的名称,所以,\foldermusichellohello.mp4下面的regex_replace会有问题。

std::string new_filename = "goodbye";
std::string sz_new_file_name_path = boost::regex_replace(complete_file_name_path, old_filename, new_filename);

所以我可以稍后,

boost::filesystem::rename(complete_file_name_path, sz_new_file_name_path);

查找和替换是完全没有必要的,因为您已经拥有了构建新路径所需的所有组件。

代替

std::string sz_new_file_name_path = boost::regex_replace(complete_file_name_path, old_filename, new_filename);

// path + newFileName + ext
std::string sz_new_file_name_path = rm.format("$1") + "\" + new_filename + "." + rm.format("$3")

您可以将组件分开,看看您有什么:

^(.*?)\?([^\]+).([a-zA-Z0-9]+)$
编辑或更不具体的^(.*?)\?([^\]+).([^.]+)$非验证

$1 = path$2 = filename$3 = extension

不捕获路径、文件名和扩展名之间的分隔符。
有了这些信息,您就可以构建自己的新字符串。

如果你想专门搜索比如mp4,像这样就可以了:

^(.*?)\?([^\]+).mp4$