Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R:how to get grep to return the match, rather than the whole string

Tags:

regex

r

I have what is probably a really dumb grep in R question. Apologies, because this seems like it should be so easy - I'm obviously just missing something.

I have a vector of strings, let's call it alice. Some of alice is printed out below:

T.8EFF.SP.OT1.D5.VSVOVA#4    T.8EFF.SP.OT1.D6.LISOVA#1   T.8EFF.SP.OT1.D6.LISOVA#2    T.8EFF.SP.OT1.D6.LISOVA#3   T.8EFF.SP.OT1.D6.VSVOVA#4     T.8EFF.SP.OT1.D8.VSVOVA#3   T.8EFF.SP.OT1.D8.VSVOVA#4    T.8MEM.SP#1                 T.8MEM.SP#3                       T.8MEM.SP.OT1.D106.VSVOVA#2  T.8MEM.SP.OT1.D45.LISOVA#1   T.8MEM.SP.OT1.D45.LISOVA#3 

I'd like grep to give me the number after the D that appears in some of these strings, conditional on the string containing "LIS" and an empty string or something otherwise.

I was hoping that grep would return me the value of a capturing group rather than the whole string. Here's my R-flavoured regexp:

pattern <- (?<=\\.D)([0-9]+)(?=.LIS) 

nothing too complicated. But in order to get what I'm after, rather than just using grep(pattern, alice, value = TRUE, perl = TRUE) I'm doing the following, which seems bad:

reg.out <- regexpr(     "(?<=\\.D)[0-9]+(?=.LIS)",     alice,     perl=TRUE ) substr(alice,reg.out,reg.out + attr(reg.out,"match.length")-1) 

Looking at it now it doesn't seem too ugly, but the amount of messing about it's taken to get this utterly trivial thing working has been embarrassing. Anyone any pointers about how to go about this properly?

Bonus marks for pointing me to a webpage that explains the difference between whatever I access with $,@ and attr.

like image 227
Mike Dewar Avatar asked Jun 03 '10 19:06

Mike Dewar


2 Answers

Try the stringr package:

library(stringr) str_match(alice, ".*\\.D([0-9]+)\\.LIS.*")[, 2] 
like image 193
hadley Avatar answered Oct 03 '22 02:10

hadley


You can do something like this:

pat <- ".*\\.D([0-9]+)\\.LIS.*" sub(pat, "\\1", alice) 

If you only want the subset of alice where your pattern matches, try this:

pat <- ".*\\.D([0-9]+)\\.LIS.*" sub(pat, "\\1", alice[grepl(pat, alice)]) 
like image 29
Ken Williams Avatar answered Oct 03 '22 00:10

Ken Williams