3 回答

TA貢獻(xiàn)1829條經(jīng)驗(yàn) 獲得超6個(gè)贊
您可以使用str_matchwith STR1 (.*?) STR2(請注意,如果您只想匹配兩者之間的任何內(nèi)容STR1并STR2使用,則空格是“有意義的” STR1(.*?)STR2)。如果出現(xiàn)多次,請使用str_match_all。
library(stringr)
a<-" anything goes here, STR1 GET_ME STR2, anything goes here"
res <- str_match(a, "STR1 (.*?) STR2")
res[,2]
[1] "GET_ME"
使用基數(shù)R的另一種方法regexec(獲得第一個(gè)匹配項(xiàng)):
test = " anything goes here, STR1 GET_ME STR2, anything goes here STR1 GET_ME2 STR2"
pattern="STR1 (.*?) STR2"
result <- regmatches(test,regexec(pattern,test))
result[[1]][2]
[1] "GET_ME"

TA貢獻(xiàn)1833條經(jīng)驗(yàn) 獲得超4個(gè)贊
這是使用基數(shù)R的另一種方法
a<-" anything goes here, STR1 GET_ME STR2, anything goes here"
gsub(".*STR1 (.+) STR2.*", "\\1", a)
輸出:
[1] "GET_ME"

TA貢獻(xiàn)1852條經(jīng)驗(yàn) 獲得超1個(gè)贊
另一種選擇是用于qdapRegex::ex_between提取左右邊界之間的字符串
qdapRegex::ex_between(a, "STR1", "STR2")[[1]]
#[1] "GET_ME"
它還適用于多次出現(xiàn)
a <- "anything STR1 GET_ME STR2, anything goes here, STR1 again get me STR2"
qdapRegex::ex_between(a, "STR1", "STR2")[[1]]
#[1] "GET_ME" "again get me"
或多個(gè)左右邊界
a <- "anything STR1 GET_ME STR2, anything goes here, STR4 again get me STR5"
qdapRegex::ex_between(a, c("STR1", "STR4"), c("STR2", "STR5"))[[1]]
#[1] "GET_ME" "again get me"
第一次捕獲在“ STR1”和“ STR2”之間,而第二次捕獲在“ STR4”和“ STR5”之間。
- 3 回答
- 0 關(guān)注
- 2830 瀏覽
添加回答
舉報(bào)