问题
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