Home > OS >  how to extract a string between two strings in R
how to extract a string between two strings in R

Time:12-03

If i have a string column in a dataframe :

     a=c ("yhj-22k_loki_res","jh_22k_lok_res","fgdjh_22k_lk_res","jhkkl_kkff_22k_lo_res","j_22k_mm_res","ko-jh_22k_lm_res")

I want to extract whatever between 22k_ and _res

         "loki","lok","lk","lo","mm","lm"

CodePudding user response:

Use a regex lookaround to extract characters (.*) that succeed after the substring "22k_" and precedes "_res"

library(stringr)
str_extract(a, "(?<=22k_).*(?=_res)")
[1] "loki" "lok"  "lk"   "lo"   "mm"   "lm"  
  •  Tags:  
  • r
  • Related