How to match nothing [duplicate]

久未见 提交于 2020-06-29 03:37:29

问题


This may be a simple question to some: how do you actually match nothing using regex in R? Suppose you have a vector of strings such as this:

q <- c("a", "12", "0", "", "300")

And suppose further you want to match the empty string "", how to go about this? It seems one can reasonably well match "" using grep to match the metacharacter . meaning 'any character', either as such or as the content of a negated character class, as well as the argument invert = T to match the opposite of the match:

grep(".", q, value = T, invert = T)
[1] ""

grep("[^.]", q, value = T, invert = T)
[1] ""

In either case the match works. But, surely, using invert feels like a convenient trick but not like a serious regex. Is there another way of matching nothing in R?


回答1:


One option would be to specify the ^ for start of the string followed by $ as the end of the string

grep("^$", q)

Or with nchar

which(nchar(q) == 0)


来源:https://stackoverflow.com/questions/62416394/how-to-match-nothing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!