Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

substring of a path variable

Tags:

regex

r

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!

like image 982
adibender Avatar asked Dec 20 '22 10:12

adibender


2 Answers

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"
  • It looks for zero or more occurences of anything .*
  • followed by a forward slash /
  • followed by anything that is not a forward slash [^/] (inside the brackets, ^ means "not"), one or more times +.
  • followed by a dot \\.
  • followed by anything zero 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)

like image 137
GSee Avatar answered Dec 30 '22 22:12

GSee


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"
like image 30
Josh O'Brien Avatar answered Dec 30 '22 20:12

Josh O'Brien