当找不到匹配时,gsub会返回一个空字符串 [英] gsub return an empty string when no match is found

查看:96
本文介绍了当找不到匹配时,gsub会返回一个空字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用R中的 gsub 函数在文本列表中返回我的模式(参考数字)的出现次数。这很有效,除非找不到匹配,在这种情况下,我得到整个字符串,而不是空字符串。考虑下面的例子:

  data<  -  list(带引文的句子(Ref。12),
另一个没有引用的句子)

sapply(data,function(x)gsub(。*(Ref。(\\d +))。*,\\1 ,x))

返回:

<$ p
$ / code> [1]Ref。12另一个没有参考的句子
$ / pre>

但我希望得到

  [1]Ref。12

谢谢!

解决方案

I 'd可能会走不同的路线,因为 sapply 对我来说似乎不是必要的,因为这些函数已经被向量化了:

  fun < -  function(x){
ind < - grep(。*(Ref。(\\\d +))。*,x ,value = FALSE)
x < - gsub(。*(Ref。(\\d +))。*,\\1,x)
x [-ind] < -
x
}

fun(data)


I'm using the gsub function in R to return occurrences of my pattern (reference numbers) on a list of text. This works great unless no match is found, in which case I get the entire string back, instead of an empty string. Consider the example:

data <- list("a sentence with citation (Ref. 12)",
             "another sentence without reference")

sapply(data, function(x) gsub(".*(Ref. (\\d+)).*", "\\1", x))

Returns:

[1] "Ref. 12"                            "another sentence without reference"

But I'd like to get

[1] "Ref. 12"                            ""

Thanks!

解决方案

I'd probably go a different route, since the sapply doesn't seem necessary to me as these functions are vectorized already:

fun <- function(x){
    ind <- grep(".*(Ref. (\\d+)).*",x,value = FALSE)
    x <- gsub(".*(Ref. (\\d+)).*", "\\1", x)
    x[-ind] <- ""
    x
}

fun(data)

这篇关于当找不到匹配时,gsub会返回一个空字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆