user3375672 user3375672 - 8 days ago 7
R Question

R regex extract numbers from string depending of context

s <- c('abc_1_efg', 'efg_2', 'hi2jk_lmn', 'opq')


How can I use a regex to get the numbers that are beside at least one underscore ("_"). In effect I would like to get outputs like this :

> output # The result
[1] 1 2
> output_l # Alternatively
[1] TRUE TRUE FALSE FALSE

Answer

We can use regex lookarounds

grep("(?<=_)\\d+", s, perl = TRUE)
grepl("(?<=_)\\d+", s, perl = TRUE)
#[1]  TRUE  TRUE FALSE FALSE