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

RRegex

R Problem Overview


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.

R Solutions


Solution 1 - R

Try the stringr package:

library(stringr)
str_match(alice, ".*\\.D([0-9]+)\\.LIS.*")[, 2]

Solution 2 - R

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)])

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike DewarView Question on Stackoverflow
Solution 1 - RhadleyView Answer on Stackoverflow
Solution 2 - RKen WilliamsView Answer on Stackoverflow