Tushar Lad
Tushar Lad

Reputation: 484

How to remove specific pattern in string?

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.

Upvotes: 3

Views: 75

Answers (3)

Pragadeesh waran
Pragadeesh waran

Reputation: 83

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

Upvotes: 0

Onyambu
Onyambu

Reputation: 79358

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"

Upvotes: 4

Tim Biegeleisen
Tim Biegeleisen

Reputation: 522762

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"

Upvotes: 1

Related Questions