Extract file extension from file path

前端 未结 5 1356
太阳男子
太阳男子 2020-12-03 09:51

How can I extract the extension of a file given a file path as a character? I know I can do this via regular expression regexpr(\"\\\\.([[:alnum:]]+)$\", x), b

5条回答
  •  [愿得一人]
    2020-12-03 10:06

    The regexpr above fails if the extension contains non-alnum (see e.g. https://en.wikipedia.org/wiki/List_of_filename_extensions) As an altenative one may use the following function:

    getFileNameExtension <- function (fn) {
    # remove a path
    splitted    <- strsplit(x=fn, split='/')[[1]]   
    # or use .Platform$file.sep in stead of '/'
    fn          <- splitted [length(splitted)]
    ext         <- ''
    splitted    <- strsplit(x=fn, split='\\.')[[1]]
    l           <-length (splitted)
    if (l > 1 && sum(splitted[1:(l-1)] != ''))  ext <-splitted [l] 
    # the extention must be the suffix of a non-empty name    
    ext
    

    }

提交回复
热议问题