user1320502 user1320502 - 2 months ago 16
R Question

regex, extract string between /

If I have these strings:

mystrings <- c("X2/D2/F4",
"X10/D9/F4",
"X3/D22/F4",
"X9/D22/F9")


How can I extract
2,9,22,22
. These characters are between the
/
and after the first character within the
/
.

I would like to do this in a vectorized fashion and add the new column with
transfrom
if possible with which I am familiar.

I think this regex gets me somewhere near all the characters within
\
:

^.*\\'(.*)'\\.*$

Answer

as.numeric(gsub("^.*D([0-9]+).*$", "\\1", mystrings))

Comments