tags:

views:

255

answers:

2

Hi, 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.

+5  A: 

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)])
Ken Williams
http://xkcd.com/208/
Marek
awesome. Thanks so much. I hadn't thought of replacing the line with the match, rather I was obsessively thinking "why on earth won't it return me the match arggghhh!". I should probably stop using those lookahead and lookbehind things as well eh? My brain doesn't work with regexp very well yet. I seem to think backwards.
Mike Dewar
Farrel
+3  A: 

Try the stringr package:

library(stringr)
str_match(alice, ".*\\.D([0-9]+)\\.LIS.*")[, 2]
hadley
brilliant. Don't suppose there are plans for stringr to use perl regexps? Or is it generally the case that one should always use R's dialect?
Mike Dewar