我有这样的条件:
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,它就不会从每个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" 发布于 2020-07-08 11:57:41
您可以使用stringr::str_match_all解决方案(因为stringr::str_extract_all“丢失”了所有捕获的子字符串):
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")
res <- stringr::str_match_all(test, "(?=(\\boh\\b(?:(?!\\boh\\b).)*?\\bwell\\b|\\bwell\\b(?:(?!\\bwell\\b).)*?\\boh\\b))")
unlist(lapply(res, function(x) x[,-1]))详细信息
(?= -积极展望的开始:( -捕获组的开始:\boh\b(?:(?!\boh\b).)*?\bwell\b - oh整词,然后是任何0+字符,尽可能少地不把一个完整的单词oh开头,直到最左边的well整词。| -或\bwell\b(?:(?!\bwell\b).)*?\boh\b - well整词,然后是任何0+字符,尽可能少地不把一个完整的单词well开头,直到最左边的oh整词。- `)` - end of the capturing group) -正面展望的结束。输出:
[1] "oh i mean well" "well he 's like oh"
[3] "well he did n't say oh" "oh he said f** well"
[5] "oh you know well" "well maybe he thought oh"
[7] "oh well" "oh my god well"
[9] "well what the hell did he oh"发布于 2020-07-08 11:59:29
您可以使用str_extract_all,一个用于oh...well,另一个用于well...oh,使用正则表达式:
library(stringr)
unlist(c(str_extract_all(test, "\\boh\\b.*?\\bwell\\b")
, str_extract_all(test, "\\bwell\\b.*?\\boh\\b")))
#[1] "oh i mean well"
#[2] "oh he said f** well"
#[3] "oh you know well"
#[4] "oh well"
#[5] "oh my god well"
#[6] "well i do n't know well he 's like oh"
#[7] "well he did n't say oh"
#[8] "well why well maybe he thought oh"
#[9] "well what the hell did he oh" 或者如果是最短的序列:
unlist(c(str_extract_all(test, "\\boh\\b((?!\\boh\\b).)*?\\bwell\\b")
, str_extract_all(test, "\\bwell\\b((?!\\bwell\\b).)*?\\boh\\b")))
#[1] "oh i mean well" "oh he said f** well"
#[3] "oh you know well" "oh well"
#[5] "oh my god well" "well he 's like oh"
#[7] "well he did n't say oh" "well maybe he thought oh"
#[9] "well what the hell did he oh"数据:
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")https://stackoverflow.com/questions/62794046
复制相似问题