How to find pattern next to a given string using regex in R -


i have string formatted example "segmentation_level1_id_10" , extract level number associated (i.e. number directly after word level).

i have solution in 2 steps, first finds pattern level\\d+ replaces level missing after, know if it's possible in 1 step str_extract

example below:

library(stringr)  segmentation_id <- "segmentation_level1_id_10"  segmentation_level <- str_replace(str_extract(segmentation_id, "level\\d+"), "level", "") 

one way using stringr library str_extract function regex featuring lookbehind:

> library(stringr) > s = "segmentation_level1_id_10" > str_extract(s, "(?<=level)\\d+") ## or make sure match level after _: str_extract(s, "(?<=_level)\\d+") [1] "1" 

or using str_match allows extracting captured group texts:

> str_match(s, "_level(\\d+)")[,2] [1] "1" 

it can done base r using gsub , making use of same capturing mechanism used in str_match, using backreference restore captured text in replacement result:

> gsub("^.*level(\\d+).*", "\\1", s) [1] "1" 

Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -