Reputation: 459
I am having a regex replace issue that i can't seem to figure out for replacing some configured parameter for a file path.
Here is what I have so far:
The regex for a filepath may not be perfect but it seems to work ok.
regex: ^(?<path>[^\\/*?<>|]+)\\\\(?<filename>.+)\\.(?<ext>.mp4$)
file name match results name: $2
So what this is doing is searching a listing of files where the extension is mp4 and using the configured match result, it will return that as a "file name".
Target string examples,
\\\\folder\music\hello.mp4
result filename = "hello"
What I would like to do is be able to take either the results from a regex match and be able to replace the name of the file/extension/path by a configured setting.
So If someone wanted for all the matched results to replace the file name with "goodbye", how would i accomplish this. This is what i have now.
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
What appears to work but limits it to a filename where the folder is not the same name so, \\folder\music\hello\hello.mp4 would have issues with the regex_replace below.
std::string new_filename = "goodbye";
std::string sz_new_file_name_path = boost::regex_replace(complete_file_name_path, old_filename, new_filename);
so i can later,
boost::filesystem::rename(complete_file_name_path, sz_new_file_name_path);
Any help would be appreciated.
Upvotes: 1
Views: 3996
Reputation:
You could probably split out the components to see what you have with:
^(.*?)\\?([^\\]+)\.([a-zA-Z0-9]+)$
edit or even less specific ^(.*?)\\?([^\\]+)\.([^.]+)$
non-validating
$1 = path $2 = filename $3 = extension
The separator between path, filename and extension are not captured.
With this information you could construct your own new string.
If you want to specifically search for say mp4's something like this would work:
^(.*?)\\?([^\\]+)\.mp4$
Upvotes: 0
Reputation: 21086
Find and replace is completely unnecessary because you already have all of the components you need to build the new path.
REPLACE
std::string sz_new_file_name_path = boost::regex_replace(complete_file_name_path, old_filename, new_filename);
WITH
// path + newFileName + ext
std::string sz_new_file_name_path = rm.format("$1") + "\\" + new_filename + "." + rm.format("$3")
Upvotes: 1