I have a dataframe, with a column with entries in the format of:
/textIwant
/textIwant/otherstuff
/
I want to create a new column extracting the "textIwant". Should I be using strsplit, or regex?
We can use str_extract
to extract one or more characters that are not a /
library(stringr)
str_extract(str1, "[^/]+")
#[1] "textIwant" "textIwant" "abc-def-ghi" "abc-def-ghi"
Or with sub
from base R
to match the characters that are not a /
, capture it as a group (([^/]+)
) and replace with the backreference (\\1
)
sub("^.([^/]+).*", "\\1", str1)
#[1] "textIwant" "textIwant" "abc-def-ghi" "abc-def-ghi"
str1 <- c("/textIwant", "/textIwant/otherstuff", "/abc-def-ghi/", "/abc-def-ghi")
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments