How to remove specific pattern in string?

Viewed 67

I have data in that string is like f <- "./DAYA-1178/10TH FEB.xlsx". I would like to extract only DAYA-1178

what I have tried is

f1 <- gsub(".*./","", f) 

But it is giving last result of my file "10TH FEB.xlsx"

Appreciate any lead.

3 Answers

It seems you are dealing with files. You need the basename of the directory:

basename(dirname(f))
[1] "DAYA-1178"

or you could do:

sub(".*/","",dirname(f))
[1] "DAYA-1178"

Using strsplit, we can split the input on path separator / and retain the second element:

f <- "./DAYA-1178/10TH FEB.xlsx"
unlist(strsplit(f, "/"))[2]
[1] "DAYA-1178"

If you wish to use sub, here is one way:

sub("^.*/(.*?)/.*$", "\\1", f)
[1] "DAYA-1178"
f1 <- gsub("[.,xlsx]","",f)

u can try like these it will give

f1 <- /DAYA-1178/10TH FEB

f3 <- strsplit(f1,"/")[[1]][2]

DAYA-1178 --> answer
Related