Get filename without extension in R

后端 未结 7 1907
野趣味
野趣味 2020-12-01 05:56

I have a file

ABCD.csv 

The length before the .csv is not fixed and vary to any length.

How can I extract the portion

7条回答
  •  星月不相逢
    2020-12-01 06:27

    Loading the library needed :

    > library(stringr)
    

    Extracting all the matches from the regex:

    > str_match("ABCD.csv", "(.*)\\..*$")
         [,1]       [,2]  
    [1,] "ABCD.csv" "ABCD"
    

    Returning only the second part of the result, which corresponds to the group matching the file name:

    > str_match("ABCD.csv", "(.*)\\..*$")[,2]
    [1] "ABCD"
    

    EDIT for @U-10-Forward:

    It is basically the same principle as the other answer. Just that I found this solution more robust.

    Regex wise it means:

    • () = group

    • .* = any single character except the newline character any number of time

    • // is escape notation, thus //. means literally "."

    • .* = any characters any number of time again

    • $ means should be at the end of the input string

    The logic is then that it will return the group preceding a "." followed by a group of characters at the end of the string (which equals the file extension in this case).

提交回复
热议问题