regex - 提取字符向量中两个特定单词之间的所有单词

标签 regex string r

有没有更有效的方法?如果没有 stringr 我怎么能做到这一点?

txt <- "I want to extract the words between this and that, this goes with that, this is a long way from that"

library(stringr)
w_start <- "this"
w_end <- "that"
pattern <- paste0(w_start, "(.*?)", w_end)
wordsbetween <- unlist(str_extract_all(txt, pattern))
gsub("^\\s+|\\s+$", "", str_sub(wordsbetween, nchar(w_start)+1, -nchar(w_end)-1))
[1] "and"                "goes with"          "is a long way from"

最佳答案

这是我在 qdap 中使用的一种方法:

使用 qdap:

library(qdap)
genXtract(txt, "this", "that")

## > genXtract(txt, "this", "that")
##         this  :  that1         this  :  that2         this  :  that3 
##                " and "          " goes with " " is a long way from " 

没有附加包:
regmatches(txt, gregexpr("(?<=this).*?(?=that)", txt, perl=TRUE))

## > regmatches(txt, gregexpr("(?<=this).*?(?=that)", txt, perl=TRUE))
## [[1]]
## [1] " and "                " goes with "          " is a long way from "

关于regex - 提取字符向量中两个特定单词之间的所有单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16161573/

相关文章:

javascript - 使用正则表达式替换除了第一次出现的空白子串之外的所有内容

python - 将单引号字符串转换为双引号字符串

c - 反向显示输出的程序流程

r - 获取第一个非 0 值或最后一个 0 值(如果仅此而已)

r - 将任何比例四舍五入为其最接近的 1/r 形式的算法

python - 日期的正则表达式在 python 的 RE 模块中不匹配

regex - 为什么使用 ^[\s\u200c]+|[\s\u200c]+$ 来修剪空格?

C# 正则表达式包含 []

c - 使用 snprintf 进行字符串连接

r - 数字的近似匹配函数