Deepesh Deepesh - 10 days ago 6
R Question

Splitting the string with the file extension in R

I'm trying to get the last number from the filename for which I used

strsplit
in R but the splitted value is getting attached with the file extension which I want to get rid of, here is what I have tried

fnames <- basename("D:/Processed files/ABC_4.csv")
strsplit(fnames,"_")


Output

"ABC" "4.csv"


alternatively I tried doing
strsplit(fnames,"_ .")
also

Any help would be much appreciated,Thanks

Answer

We can try with gsub

as.numeric(gsub("\\D+", "", fnames))
#[1] 4

Or

as.numeric(gsub("^.*_|[^0-9]+$", "", fnames))

Or with stri_extract_last

library(stringi)
as.numeric(stri_extract_last_regex(fnames, "\\d+"))
#[1] 4
Comments