【发布时间】:2020-07-08 11:42:40
【问题描述】:
我有这样的字符串:
test <- c("oh i mean well i do n't know well he 's like oh",
"yeah so well he did n't say oh he said f** well you know what he 's like",
"oh you know well why well maybe he thought oh well good",
"oh my god well what the hell did he oh you know")
我想匹配以oh 开头并以well 结尾的所有单词序列,反之亦然,以well 开头并以oh 结尾。 str_extract_all 的这种使用确实匹配了一些目标序列,但不是全部,因为它无法迭代匹配,也就是说,它不会从每个oh 或well 重新开始一次它在比赛中消耗了它:
library(stringr)
strings <- unlist(str_extract_all(test, "\\boh\\b.*?\\bwell\\b|\\bwell\\b.*?\\boh\\b"))
[1] "oh i mean well" "well he 's like oh" "well he did n't say oh" "oh you know well"
[5] "well maybe he thought oh" "oh my god well"
完整的输出是这样的:
[1] "oh i mean well" "well he 's like oh" "well he did n't say oh" "oh he said f** well"
[5] "oh you know well" "oh well" "well maybe he thought oh" "oh my god well"
[9] "well what the hell did he oh"
【问题讨论】:
-
怎么样:
c(unlist(str_extract_all(test, "\\boh\\b.*?\\bwell\\b")), unlist(str_extract_all(test, "\\bwell\\b.*?\\boh\\b")))? -
你能把它分成两个正则表达式吗?...即
c(unlist(str_extract_all(test, "\\boh\\b.*?\\bwell\\b")), unlist(str_extract_all(test, "\\bwell\\b.*?\\boh\\b"))) -
改用非消耗性环视集群。对于交替的第一方面,它将是
(?<=\\boh\\b).*?(?=\\bwell\\b) -
我会让@GKi按照他一分钟前发布的那样做:)
-
@Sotos 太好了!