3 回答

TA貢獻1829條經驗 獲得超6個贊
您可以使用str_matchwith STR1 (.*?) STR2(請注意,如果您只想匹配兩者之間的任何內容STR1并STR2使用,則空格是“有意義的” STR1(.*?)STR2)。如果出現多次,請使用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"
使用基數R的另一種方法regexec(獲得第一個匹配項):
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貢獻1833條經驗 獲得超4個贊
這是使用基數R的另一種方法
a<-" anything goes here, STR1 GET_ME STR2, anything goes here"
gsub(".*STR1 (.+) STR2.*", "\\1", a)
輸出:
[1] "GET_ME"

TA貢獻1852條經驗 獲得超1個贊
另一種選擇是用于qdapRegex::ex_between提取左右邊界之間的字符串
qdapRegex::ex_between(a, "STR1", "STR2")[[1]]
#[1] "GET_ME"
它還適用于多次出現
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"
或多個左右邊界
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 關注
- 2833 瀏覽
添加回答
舉報