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

前端 未结 2 1286
眼角桃花
眼角桃花 2020-12-22 23:33

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.

相关标签:
2条回答
  • 2020-12-23 00:09

    Try the stringr package:

    library(stringr)
    str_match(alice, ".*\\.D([0-9]+)\\.LIS.*")[, 2]
    
    0 讨论(0)
  • 2020-12-23 00:24

    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)])
    
    0 讨论(0)
提交回复
热议问题