【发布时间】:2011-08-11 19:18:54
【问题描述】:
我遇到了一个正则表达式替换问题,我似乎无法解决替换文件路径的某些配置参数的问题。
这是我目前所拥有的:
文件路径的正则表达式可能并不完美,但似乎可以正常工作。
正则表达式:^(?<path>[^\\/*?<>|]+)\\\\(?<filename>.+)\\.(?<ext>.mp4$)
文件名匹配结果名称:$2
所以这是在搜索扩展名为 mp4 的文件列表,并使用配置的匹配结果,它将作为“文件名”返回。
目标字符串示例,
\\\\folder\music\hello.mp4
结果文件名 = "你好"
我想做的是能够从正则表达式匹配中获取结果,并能够用配置的设置替换文件/扩展名/路径的名称。
因此,如果有人希望所有匹配的结果都用“再见”替换文件名,我将如何做到这一点。这就是我现在所拥有的。
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 = "\\folder\music\hello.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
似乎可行,但将其限制为文件夹名称不同的文件名,因此, \\folder\music\hello\hello.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);
任何帮助将不胜感激。
【问题讨论】: