Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/82.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Regex gsub一段中的单词列表_Regex_R - Fatal编程技术网

Regex gsub一段中的单词列表

Regex gsub一段中的单词列表,regex,r,Regex,R,给定以下代码: list = c("the", "at", "ok") paragraph = "the cat ath the hat is ok" 如何从“段落”中删除列表中的所有单词 我试着做: gsublist,第2段 但只删除了列表中的第一项。我知道这不应该很复杂,但这仍然让我困惑。另外,我希望避免使用for循环,但是apply族应该可以 模式| at | ok将匹配列表中任何字符串的出现 不过,听起来好像你想匹配那些实际的单词,而不是它们所属的单词,即匹配但不匹配then、at但不

给定以下代码:

list = c("the", "at", "ok")
paragraph = "the cat ath the hat is ok"
如何从“段落”中删除列表中的所有单词

我试着做:

gsublist,第2段

但只删除了列表中的第一项。我知道这不应该很复杂,但这仍然让我困惑。另外,我希望避免使用for循环,但是apply族应该可以

模式| at | ok将匹配列表中任何字符串的出现

不过,听起来好像你想匹配那些实际的单词,而不是它们所属的单词,即匹配但不匹配then、at但不匹配Cratter等。如果是这样,你可以使用模式\\b the | at | ok\\b其中\\b是匹配单词边界的模式

您可以使用paste0从匹配词的任意向量构造所需的模式:

list <- c("the", "at", "ok")
paragraph <- "the cat ath the hat is ok"

## Construct the regular expression
pat <- paste0("\\b(", paste0(list, collapse="|"), ")\\b")    
pat
# [1] "\\b(the|at|ok)\\b"

## Use it
gsub(pat, "", paragraph)
# [1] " cat ath  hat is "

谢谢你的回答。有更自然的方法吗?@user1103294我想我们会发现的!与此相关的是,我想知道这是更快、更慢,还是与在for循环中一次处理一个单词的速度相同。在任何情况下,这都是有效的,所以至少这是可行的@user1103294 josh的反应很自然。除非段落包含多个字符串,否则可能不会使用apply。顺便说一句,不要调用变量列表@anthonydamico我认为显式使用某种循环是一种更自然的方式。这就是为什么我认为他的答案很聪明的部分原因,他不聪明。@user1103294你说过,plz不用于循环: