【发布时间】:2012-04-18 17:23:07
【问题描述】:
我在 R 中使用 gsub 函数在文本列表中返回我的模式(参考编号)的出现。除非找不到匹配项,否则这很好用,在这种情况下,我会取回整个字符串,而不是空字符串。考虑这个例子:
data <- list("a sentence with citation (Ref. 12)",
"another sentence without reference")
sapply(data, function(x) gsub(".*(Ref. (\\d+)).*", "\\1", x))
返回:
[1] "Ref. 12" "another sentence without reference"
但我想得到
[1] "Ref. 12" ""
谢谢!
【问题讨论】:
-
gsub不能(当前为 2.15.0)这样做,因为:“如果replacement包含未在pattern中定义的反向引用,则结果未定义(但通常采用反向引用成为"")。”