I have a path like this ../some/thing/foobar/foobar.happening
and I want the character
string between the last /
and .
.
I realize this will be easy for some, but I'm not yet familiar with regular expressions etc.
I also probably could do this by myself with strsplit
, but I'm looking for an elegant one-liner, if possible.
Thanks in advance!
basename
will give you the part after the last slash. Then, you can split on the dot (which you have to escape with two \
)
> (name <- basename("../some/thing/foobar/foobar.happening"))
[1] "foobar.happening"
> unlist(strsplit(name, "\\."))
[1] "foobar" "happening"
Then select the first element
> unlist(strsplit(name, "\\."))[1]
[1] "foobar"
I see you actually asked for a way other than strsplit
. Here's a regular expression
> sub(".*/([^/]+)\\..*", "\\1", "../some/thing/foobar/foobar.happening")
[1] "foobar"
.*
/
[^/]
(inside the brackets, ^
means "not"), one or more times +
. \\.
.*
. Then it replaces that with only the stuff inside the parenthesis [^/]+
which is everything between the forward slash and the dot. The \\1
means the stuff inside the first set of parenthesis. (there's only one set in this case, but if there were a second we could refer to it with \\2
)
You could use a combination of basename()
and file_path_sans_ext()
. (The latter comes from the tools package, which ships with the basic R distribution.)
path <- "../some/thing/foobar/foobar.happening"
library(tools)
file_path_sans_ext(basename(path))
# [1] "foobar"
## Or, if you don't want to load the tools package
tools::file_path_sans_ext(basename(path))
# [1] "foobar"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With