Read characters with grep

I have this character

I would like to use the Grep function, or something like that, to make me return specific parts.
I explain myself. I would like to write a function that would return everything before the first slash "/".
then another line in which is returned what is between the first "/" and the second "/".

to be clear,
it should return,
in the first case "101".
in the second case "Testler Export"

I think you want to do something like this

string <- "101/Testler Export/somthing/shomething else.txt"
strsplit(string, "/")[[1]][1:2]
#> [1] "101"            "Testler Export"

Created on 2019-02-09 by the reprex package (v0.2.1)

For future posts please ask your questions with a REPRoducible EXample (reprex). A reprex makes it much easier for others to understand your issue and figure out how to help.

If you've never heard of a reprex before, you might want to start by reading this FAQ:

2 Likes

sorry, i'm new in this community. i'm a beginner whith R, can you tell me what this command mean

[[1]][1:2]

I understood how to use them, but to understand more fully their meaning. also you could advise me, where I can learn this syntax of R. for example, I refer to the use that you made of square brackets, etc ..
Sorry in advance if I made mistakes on how to publish on the site

Those commands are for subsetting lists and vectors, this section of the free online book "R Programming for Data Science" explains this very well.

1 Like

strsplit(string, '/') returns a list, of the same length as string itself (in this case 1).

So, here [[1]] returns the first element of that list, which is a vector c( '101', 'Testler Export', 'somthing', 'shomething else.txt')

Finally, [1:2] returns the first two elements of that vector, i.e. c('101', 'Testler Export').

string <- '101/Testler Export/somthing/shomething else.txt'

(split <- strsplit(x = string,
                  split = '/'))
#> [[1]]
#> [1] "101"                 "Testler Export"      "somthing"           
#> [4] "shomething else.txt"

(split_1 <- split[[1]])
#> [1] "101"                 "Testler Export"      "somthing"           
#> [4] "shomething else.txt"

(split_1_1n2 <- split_1[1:2])
#> [1] "101"            "Testler Export"
2 Likes

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.