如何不匹配 [英] How to match nothing
问题描述
对于某些人来说,这可能是一个简单的问题:您如何在 R 中使用正则表达式实际上不匹配任何内容?假设你有一个像这样的字符串向量:
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")
再假设你想匹配空字符串""
,怎么做呢?似乎可以合理地匹配 ""
使用 grep
来匹配元字符 .
意思是任何字符",无论是这样还是作为内容否定字符类,以及参数 invert = T
以匹配匹配的反面:
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] ""
在任何一种情况下,匹配都有效.但是,当然,使用 invert
感觉像是一个方便的技巧,但不像一个严肃的正则表达式.有没有另一种方法可以匹配 R 中的任何内容?
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?
推荐答案
一种选择是指定 ^
作为字符串的开头,然后是 $
作为结尾字符串
One option would be to specify the ^
for start of the string followed by $
as the end of the string
grep("^$", q)
或者用 nchar
which(nchar(q) == 0)
这篇关于如何不匹配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!