MAPK MAPK - 25 days ago 8
R Question

How to remove anything before and after two matching patterns in R

I have this vector

myvec <- c( "tes_1123_SS1G_340TX1", "tes_23_SS2G_340TX21")
. I want to remove anything before SS and anything after TX and get the result:
SS1G_340TX
,
SS2G_340TX
.

Answer Source

There are many ways to do this in one line. Here's one:

gsub(".*(SS.*TX).*","\\1",myvec)

[1] "SS1G_340TX" "SS2G_340TX"