搜索/替换boost正则表达式
search/replace boost regex C++
我有一个正则表达式替换问题,我似乎无法找出替换文件路径的一些配置参数。
到目前为止我写的是:
文件路径的正则表达式可能不完美,但它似乎工作得很好。
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$
相关文章:
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 为什么 Boost:正则表达式没有按预期找到所有结果?
- 使用 boost::regex 从目录中获取带有一些正则表达式的文件名称时出现意外输出
- 使用 boost::regex (c++) 比较两个正则表达式
- 我的 Boost 正则表达式与任何内容都不匹配
- 使用boost正则表达式时出现shared_ptr错误
- Boost正则表达式:链接时未定义的引用
- 如何使用perl样式内存正则表达式与Boost库匹配
- 如何获得与 C++11 或 Boost 匹配的正则表达式长度
- 递归匹配与 boost 正则表达式库
- 提高Boost正则表达式的速度或在C++中使用PCRE
- boost正则表达式中的命名捕获/组列表
- 使用Boost替换正则表达式
- 关于正则表达式与Boost的逻辑AND和OR匹配的说明
- 将 C++11 正则表达式与 gcc 4.8.2 一起使用时会出现奇怪的结果(但适用于 Boost 正则表达式)
- 使用 Boost 的 C++ 中的正则表达式
- Boost::qt Creator中的正则表达式
- 如何使 Boost.Spirit.Lex 令牌值成为匹配序列的子字符串(最好通过正则表达式匹配组)
- Boost.Test 使用正则表达式测试文件内容
- 使用 Boost::regex 进行正则表达式组匹配