如何提取两个连字符之间的单词?
Ho to extract words between two hyphens?
如何提取 R 中两个连字符之间的所有内容
ts = ("az_bna_njh","j_hj_lkiuy","ml_", "_kk")
我需要提取 bna、hj、ml 和 kk
我们可以使用
sub("^\w+_(\w+)_.*", "\1", trimws(ts, whitespace = "_"))
#[1] "bna" "hj" "ml" "kk"
或者另一种选择是
sub("^\w+_(\w+)_.*", "\1", gsub("^_|_$", "", ts))
你也可以试试:
#Data
ts = c("az_bna_njh","j_hj_lkiuy","ml_", "_kk")
#Code
gsub(".*_(.*)\_.*", "\1", trimws(ts,whitespace = '_'))
输出:
[1] "bna" "hj" "ml" "kk"
您可以尝试另一种方法
library(stringr)
str_replace_all(ts, c("^.*_(\w+)_.*$" = "\1", "^_|_$" = ""))
#[1] "bna" "hj" "ml" "kk"
如何提取 R 中两个连字符之间的所有内容
ts = ("az_bna_njh","j_hj_lkiuy","ml_", "_kk")
我需要提取 bna、hj、ml 和 kk
我们可以使用
sub("^\w+_(\w+)_.*", "\1", trimws(ts, whitespace = "_"))
#[1] "bna" "hj" "ml" "kk"
或者另一种选择是
sub("^\w+_(\w+)_.*", "\1", gsub("^_|_$", "", ts))
你也可以试试:
#Data
ts = c("az_bna_njh","j_hj_lkiuy","ml_", "_kk")
#Code
gsub(".*_(.*)\_.*", "\1", trimws(ts,whitespace = '_'))
输出:
[1] "bna" "hj" "ml" "kk"
您可以尝试另一种方法
library(stringr)
str_replace_all(ts, c("^.*_(\w+)_.*$" = "\1", "^_|_$" = ""))
#[1] "bna" "hj" "ml" "kk"