Ho to extract words between two hyphens?

Viewed 57

How to extract all between two hyphens in R

   ts = ("az_bna_njh","j_hj_lkiuy","ml_", "_kk")

I need to extract bna,hj,ml, and kk

3 Answers

We can use

 sub("^\\w+_(\\w+)_.*", "\\1", trimws(ts, whitespace = "_"))
 #[1] "bna" "hj"  "ml"  "kk"

Or another option is

 sub("^\\w+_(\\w+)_.*", "\\1", gsub("^_|_$", "", ts))

Also you can try:

#Data
ts = c("az_bna_njh","j_hj_lkiuy","ml_", "_kk")
#Code
gsub(".*_(.*)\\_.*", "\\1", trimws(ts,whitespace = '_'))

Output:

[1] "bna" "hj"  "ml"  "kk"

Another way you can try

library(stringr)
str_replace_all(ts, c("^.*_(\\w+)_.*$" = "\\1", "^_|_$" = ""))
#[1] "bna" "hj"  "ml"  "kk" 
Related