Amitai Amitai - 2 months ago 8
R Question

R regex for everything between LAST backslash and last dot

full.path = 'C:\Users\me\Desktop\Data\my_file.csv'


I can't figure out the right regex to be left with only

essential.name = 'my_file'


I'm afraid I keep on failing on encoding correctly the last backslash

Answer

We can use the basename and file_path_sans_ext (from tools) to extract the file name

tools::file_path_sans_ext(basename(full.path))
#[1] "my_file"

Or if we need regex, use gsub

gsub(".*\\\\|\\..*$", "", full.path)
#[1] "my_file"

data

full.path = 'C:\\Users\\me\\Desktop\\Data\\my_file.csv'