user4016367
user4016367

Reputation: 481

c++ regex get folder from a file path

I have a file name like this

/mnt/opt/storage/ssd/subtitles/8/vtt/2011022669-5126858992107.vtt

how to replace the file name with * using regex so I get

/mnt/opt/storage/ssd/subtitles/8/vtt/*?

I know the simple for loop split or boost::filesystem approach, I'm looking for a regex_replace approach.

Upvotes: 0

Views: 1779

Answers (3)

marcinj
marcinj

Reputation: 49986

Below is a solution with regexp_replace [live]:

   std::string path = "/mnt/opt/storage/ssd/subtitles/8/vtt/2011022669-5126858992107.vtt";
   std::regex re(R"(\/[^\/]*?\..+$)");

   std::cout << path << '\n';
   std::cout << std::regex_replace(path, re, "/*") << '\n';

outputs:

/mnt/opt/storage/ssd/subtitles/8/vtt/2011022669-5126858992107.vtt /mnt/opt/storage/ssd/subtitles/8/vtt/*

but,... regexp seems to be a bit too heavy weight for such simple replacement

Upvotes: 2

SingerOfTheFall
SingerOfTheFall

Reputation: 29966

You don't need regexp for this:

string str = "/mnt/opt/storage/ssd/subtitles/8/vtt/2011022669-5126858992107.vtt";
auto lastSlash = str.find_last_of('/');
str.replace(str.begin() + lastSlash + 1, str.end(), "*");

Upvotes: 6

Michał M
Michał M

Reputation: 618

Try this pattern

(([\w+\-])+)(?=(\.\w{3}))

tested in notepad++.

(?=()) its lookahaed. So it will match ([\w+-])+ only if extension (.\w{2,3)) in format .xxx or .xx is after this group. In c++ you have to just replace group to * something like replace (string, $1 , '*') -- i don't know c++ replace funciton, just assuming.

$1,$2,$3... its group number, in this case - $1 its (([\w+-])+).

Upvotes: 2

Related Questions